Wednesday, January 12, 2011

Posting a javascript array using jQuery to ASP.NET MVC controller action

Posting a data from a JavaScript has become a lot more easier  as more and more cool jQuery plugins continue to avail themselves on top of the core jQuery  library. In my current project I needed to post a JavaScript complex array object back to my ASP.NET MVC controller action which expects  a collection of custom objects. An example is worth a thousand words, I don't want to beat around the bush while you wait:
First the model:

and controller action:

So the idea here is to post a JavaScript array of Employee's to the controller action ExportUser, here is the JavaScript constructor for the Employee object and other utility JavaScript functions.

I like creating my JavaScript in this style, it some how allows me to modularize my script , as you see the above script contains everything we need to achieve our goal namely posting arrays of custom objects. The Employee constructor "create" begins at line number 12 and runs all the way to line number 16 in fact it very short. Never include server URLs in your JavaScript instead pass them and any other view specific data elements to your script, that is why the init method is there for. 

Or using the new Razor view engine  syntax: by the way working with razor is exciting.

I am sure this will get the message across, though the example is simplified. Now let us see the underpinnings of  the function This function wraps the jQuery ajax function inside, meaning you need to have a reference to jQuery in your view to get this up and running .The other heavy lifting is done by json2.js  at line number 23, the call toJSON() converts the input array to json format making it easier for the jQuery $.ajax function. Since we are sending the data as json the content type for the ajax request should be  application/json and this allows the MVC model binder and json value provider to reassemble the data and pass it on to the controller action. Whereas model binders are used to bind incoming data to an object model, value providers provide an abstraction for the incoming data itself. How awesome is this? Leave a comment and any questions.