Deserialising JSON into nested view model in controller

爱⌒轻易说出口 提交于 2019-12-11 05:15:22

问题


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?


回答1:


If you want that the MVC Model Binder parses your collections properly when sending data with $.ajax you need to do two things:

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

So here is the correct usage which then can be parsed by the model binder:

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


来源:https://stackoverflow.com/questions/14591437/deserialising-json-into-nested-view-model-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!