Removing JSON deserialization into a nested view model in a controller

I have a structure structure for nested views:

public class PersonViewModel { public int Height { get; set; } public List<LegViewModel> Legs {get;set;} } public class LegViewModel { public int Length { get; set; } } 

I am sending JSON to this using jQuery post:

 <script> $(function () { $("#mybutton").click(function () { $.ajax({ type: "POST", data: { Height: 23, Legs: [ { Length: 45, } ] } }); }); }); </script> <button id="mybutton">hello world!</button> 

I send a controller action to this:

 [HttpPost] public ActionResult Save(PersonViewModel model) { return Json(new { success = true }); } 

Height is filled with a PersonViewModel , as well as the number of elements in the Legs list, but each LegViewModel is not in the list: the Length property remains at 0, where I would expect the Legs array to contain one element with Length 45.

Note that this is also the same when I don't use the list at all: having the following values ​​gives the null null PersonViewModel.Legs property, but still as the Legs.Length` as 0:

 // view model public class PersonViewModel { public int Height { get; set; } //public List<LegViewModel> Legs {get;set;} public LegViewModel Leg { get; set; } } public class LegViewModel { public int Length { get; set; } } // view $("#mybutton").click(function () { $.ajax({ type: "POST", data: { Height: 23, Leg: { Length: 45, } } }); }) 

How can I populate a nested view model using JSON? Is there something I missed or MVC cannot do this?

+1
source share
1 answer

If you want MVC Model Binder to properly analyze your collections when sending data using $.ajax , you need to do two things:

  • Set contentType to 'application/json'
  • And your data should contain JSON, so JSON.stringify data

So, here is the correct use, which can then be analyzed using the model's binding object:

 $("#mybutton").click(function () { $.ajax({ type: "POST", contentType: 'application/json', data: JSON.stringify({ Height: 23, Legs: [ { Length: 45, } ] }) }); }); 
+1
source

All Articles