Wednesday, October 01, 2008
Posted on Wednesday, October 01, 2008 12:28:18 PM (Mountain Daylight Time, UTC-06:00)  Comments [0] | 
Categories: .NET | Ajax | ASP.NET MVC | Dojo

Next up in my series of posts on using dojo to communicate with a Controller class is POSTing data. In this example, I used dojo.xhrPost to send Json as a form and have the MVC framework parse it into the Create(string name, string age) method on the Services controller. In this case, the data being sent back and forth is simple - a Name and Age from two text boxes.

Dojo Code

function CreateEmployeeMVCPost(){
    var responseNode = dojo.byId("responseMVCPost");
    var request = {"name":dojo.byId("username").value , "age":parseInt(dojo.byId("age").value)};     
         
    dojo.xhrPost({
        url: '<%= Page.ResolveClientUrl("~/Service/Create") %>',
        handleAs: 'json',
        timeout:3000,
        content: request,   
        //Don't set content type to Json
        contentType: "application/x-www-form-urlencoded",
        load: function(person,args){                         
            responseNode.innerHTML = "Response: " + person.Name + " " + person.Age;
        },
        error: function(error,args){ 
            alert(error);               
            responseNode.innerHtml("Error!",error);
        }
    });
}

Controller Code

ASP.NET MVC looks at the form data and matches up form elements which have the same name as the parameters of the method. So - the in-bound json {"name":"steve", "age":34} is parsed into form elements called "name" and "age", which line up with the parameters of the method (shown below). The controller just uses the inputs to create a new instance of an Employee object, which is then Json serialized and returned to the client.

[AcceptVerbs("POST")]

public ActionResult Create(string name, string age)

{

    return Json(new Employee(name, Convert.ToInt32(age)), "text/json-comment-filtered");

}

This is pretty smooth and works very well for simple data. Next time I'll look at trying to POST complex objects.

Comments are closed.