I recently hit a requirement to take an array of objects and post them to an asp.net mvc action using JQuery’s ajax functionality.
I had to do a bit of Googling to work out how to do this so figured I’d document what I found.
The main two parts to this are getting JQuery to spit out JSON data and ASP.NET MVC to deserialize that data into a strongly typed generic list.
- creates a new array
- iterates over some table rows and grabs a couple of hidden field values for each row
- pushes the Rule instance into the array
- calls JSON.stringify to construct a valid JSON string from our array of Rules
- posts the JSON string to our destination URL
As you can see, this script effectively translates a table of values, to an array of Rules which are then sent as JSON to our target URL.
The stringify function uses the script available from here.
The next trick is to get the MVC action to accept the array and turn it into a strongly typed generic list.
As you can see we simply specify our generic list as the parameter for our action (which accepts HTTP Posts only).
JSON Model Binder
The final piece in the jigsaw is to tell MVC how to bind the JSON data to this generic list of Rules.
I found the code to create a simple JSON model binder here.
Now all you have to do is register this as the default model binder. Because it inherits the DefaultBinder, and only kicks in if the request type is application/json this shouldn’t break any non-json model binding.