Monday, September 29, 2008
Posted on Monday, September 29, 2008 7:28:29 PM (Mountain Daylight Time, UTC-06:00)  Comments [0] | 
Categories: Ajax | ASP.NET MVC | Dojo

My first exploration of using MVC with the dojo toolkit focused on GETting data from a Controller.

I created a simple ServiceController, and added a ListEmployees method. In MVC, this relates to a Url like  http://localhost/mvcajax/Service/ListEmployees. I added the AcceptVerbs attribute to restrict this action to GET's. Code is below:

[AcceptVerbs("GET")]
public ActionResult ListEmployees()
{
    List<Employee> emps = new List<Employee>();
    emps.Add(new Employee("Dave",37));
    emps.Add(new Employee("Kai", 2));
    return Json(emps, "text/json-comment-filtered");          
}

As you can see, this just creates two "employees", adds them to a strongly typed list, and returns them as Json. Super simple.

In the View, I wired things up using dojo.xhrGet, and then converted the json into an array of objects.

What's nice about this is that the json that's returned is automatically turned into objects.

<script type="text/javascript">
function GetEmployeesMVCGet(){
    var responseNode = dojo.byId("responseMVCGet");                       
    dojo.xhrGet({
        url: '<%= Page.ResolveClientUrl("~/Service/ListEmployees") %>',
        handleAs: 'json',
        timeout:3000,                    
        contentType: "application/json; charset=utf-8",
        load: function(person,args){                                     
            responseNode.innerHTML ="Response: " + person[1].Name + " " + person[1].Age;
        },
        error: function(error,args){ 
            alert(error);               
            responseNode.innerHtml("Error!",error);
        }
    });
}
</script>

You may notice that the url passed into xhrGet looks a little funky - well, this code was copied from the View in Visual Studio, so the <%= Page.ResolveClientUrl("~/Service/ListEmployees") %> has not been evaluated. When the page is served, this expression is evaluated, and the full url added in. This is much better than putting in the path manually, as it can be used the same way from any view.

So, this is very usable, and relatively easy to build and consume

Next up - posting Data with dojo.xhrPost...

Comments are closed.