I am looking for a solution for POSTing an array of MVC3 objects via JSON.
Sample code I'm working on: http://weblogs.asp.net/scottgu/archive/2010/07/27/introducing-asp-net-mvc-3-preview-1.aspx
JS:
var data = { ItemList: [ {Str: 'hi', Enabled: true} ], X: 1, Y: 2 }; $.ajax({ url: '/list/save', data: JSON.stringify(data), success: success, error: error, type: 'POST', contentType: 'application/json, charset=utf-8', dataType: 'json' });
ListViewModel.cs:
public class ListViewModel { public List<ItemViewModel> ItemList { get; set; } public float X { get; set; } public float Y { get; set; } }
ItemViewModel.cs:
public class ItemViewModel { public string Str;
ListController.cs:
public ActionResult Save(ListViewModel list) {
The result of this POST:
list is set in ListViewModel
Its X and Y properties are set. The entered ItemList property is set. The ItemList contains one item because it must. The item in this ItemList is not initialized. Str is null and Enabled is false.
In other words, this is what I get from MVC3 model binding:
list.X == 1 list.Y == 2 list.ItemList != null list.ItemList.Count == 1 list.ItemList[0] != null list.ItemList[0].Str == null
It would seem that MVC3 JsonValueProvider does not work for complex objects. How do I make this work? Do I need to modify an existing MVC3 JsonValueProvider and fix it? If so, how do I get to it and replace it in the MVC3 project?
Related StackOverflow questions that I have already pursued to no avail:
Asp.net Mvc Ajax Json (post Array) Uses MVC2 and the old forms-based encoding - this approach fails with an object that contains an array of objects (JQuery cannot encode it correctly).
Publish an array of complex objects using JSON, JQuery for ASP.NET MVC Controller Uses a hack that I would like to avoid when the controller receives a regular string, which it manually deserializes by itself rather than using a framework.
MVC3 RC2 JSON Post Binding does not work correctly It did not have its own set of content - it is installed in my code.
How to host an array of complex objects using JSON, jQuery for ASP.NET MVC Controller? This poor guy had to write JsonFilter to parse the array. Another hack I would rather avoid.
So how do I do this?