I have a nested view model structure:
public class PersonViewModel
{
public int Height { get; set; }
public List<LegViewModel> Legs {get;set;}
}
public class LegViewModel
{
public int Length { get; set; }
}
I send some 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’m posting to this controller action:
[HttpPost]
public ActionResult Save(PersonViewModel model)
{
return Json(new { success = true });
}
The Height of a PersonViewModel gets populated, as does the number of elements in the Legs list, but each LegViewModel in the list does not: 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 do not use a list at all: having the following yields a not null PersonViewModel.Legs property, but still as theLegs.Length` property 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’ve missed or can MVC not do this?
If you want that the MVC Model Binder parses your collections properly when sending data with
$.ajaxyou need to do two things:contentTypeto'application/json'datashould hold JSON soJSON.stringifythe dataSo here is the correct usage which then can be parsed by the model binder: