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.
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); } }); }
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.
I'm Dave and this is my blog. I'm usually writing about .NET Software Development, ArcGIS, or Agile Practices, but other stuff does creep in from time to time. I hope you find something of use, and feel free to contact me if you have any questions. You can also check out my profile on LinkedIn
dojo.DTSAgile.com is our technology preview / demo site. As I and my team cook up cool things we post them here.
ArcDeveloper.net is a site that hosts a set of open source projects related to ArcGIS. This includes Tile Cache for .NET (TC4N) and Feature Server for .NET (FS4N). Come over and check it out!
Assembla is a free service that provides Subversion source control, wikis and work Tracking. The ArcDeveloper project is run from here. It rocks. Check them out today.
Agilistas is a LinkedIn group focused on discussing and promoting Agile practices. Everyone is welcome to join in the conversation as we evolve the process of creating software to make it more enjoyable for all involved.