Post an Array of Objects via JSON to ASP.Net MVC3 Post an Array of Objects via JSON to ASP.Net MVC3 json json

Post an Array of Objects via JSON to ASP.Net MVC3


In addition to { get; set; }, these are some of the conditions for JSON Binding Support:

  1. This is new feature in ASP.NET MVC 3 (See “JavaScript and AJAX Improvements“).
  2. The JSON object’s strings (‘X’, ‘Y’, ‘Str’, and ‘Enabled’) must match ViewModel object’s properties.
  3. ViewModel object’s properties must have { get; set; } method.
  4. Must specify Content Type as “application/json” in the request.
  5. If it's still not working, check the JSON string to make sure it's valid one.

Read more at my post.

Hope that helps!


The problem was that the properties in the models that were in the List did not have get/set on their public properties. Put another way, MVC3's automatic JSON binding only works on object properties that have get and set.

This will not bind:

public string Str;

This will bind:

public string Str { get; set; }


That's strange. I am unable to reproduce your behavior. Here's my setup (ASP.NET MVC 3 RTM):

Model:

public class ItemViewModel{    public string Str { get; set; }    public bool Enabled { get; set; }}public class ListViewModel{    public List<ItemViewModel> ItemList { get; set; }    public float X { get; set; }    public float Y { get; set; }}

Controller:

public class HomeController : Controller{    public ActionResult Index()    {        return View();    }    [HttpPost]    public ActionResult Save(ListViewModel list)    {        return Json(list);    }}

View:

@{    ViewBag.Title = "Home Page";}<script type="text/javascript">    $(function () {        var data = { ItemList: [{ Str: 'hi', Enabled: true}], X: 1, Y: 2 };        $.ajax({            url: '@Url.Action("save", "home")',            data: JSON.stringify(data),            type: 'POST',            contentType: 'application/json',            dataType: 'json',            success: function (result) {                alert(result.ItemList[0].Str);            }        });    });</script>

Running this alerts "hi" and inside the Save action everything is correctly initialized.

And just for the record what doesn't work are Dictionaries. I've opened a ticket about the issue.