Best Practice for Lists of Complex Types in ASP.NET MVC 3

You will still need an html field (type=hidden) in order to post this data back to the server. (You could use an ajax post but this probably isn't a great idea)

I would suggest designing a reasonable object model to contain these data structures, and serializing the object model each time you make a change it to json with stringify

Then when you post back the form, the json will be sent to the server and you can deserialise the whole object model to a set of classes written in c# (which can mimic the object model you had in javascript) using the JavaScriptSerializer classes

Edit:

To deserialize a json string, you can use the following code:

JavaScriptSerializer js = new JavaScriptSerializer(); 
var c = js.Deserialize<MyClass>(json);
return View(c);

If you post back json as the post message body, (e.g. an $.ajax, or $.post method) then binding will occur automatically with MVC3, you simply have to specify the correct content type: application/json in the post; follow the link in my comment below for more details as to how this works.

Martin


Since we're going with javascript all the way through, I would stick with javascript behavior for the postback as well. As you enter new items into the list, I would continue to build up a muftidimensional javascript array, then convert the array to json before sending it via an ajax post to your MVC route.

As long as the json object conforms to the naming standards of your model, MVC will already do the implicit model binding before it gets to the action method.

What's the easiest and most elegant way to do this? Knockout.js! In knockout, you'd create an observable collection and add to your collection without the grubby syntax of javascript arrays. Then you would call the knockout toJSON method to convert the collection to json before issuing the ajax post.

I'd highly recommend the watching PluralSight video on Knockout and then downloading the source code.

I'd write a sample, but I have to get back to work :)


Have you considered using an javascript framework like backbone or knockout? https://stackoverflow.com/questions/5112899/knockout-js-vs-backbone-js-vs