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?
source share