【问题标题】:Deserialising JSON into nested view model in controller将 JSON 反序列化为控制器中的嵌套视图模型
【发布时间】:2013-01-29 20:15:28
【问题描述】:

我有一个嵌套的视图模型结构:

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

public class LegViewModel
{
    public int Length { get; set; }
}

我使用 jquery post 向此发送一些 JSON:

<script>
    $(function () {

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

我将发布到此控制器操作:

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

PersonViewModelHeight 被填充,Legs 列表中元素的 number 个也被填充,但列表中的每个 LegViewModel 都没有:Length属性保持为 0,我希望 Legs 数组包含一个具有 Length 45 的元素。

请注意,当我根本不使用列表时,这也是相同的:具有以下将产生一个不为空的PersonViewModel.Legs property, but still as theLegs.Length` 属性为 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,
                }

        }
    });
})

如何使用 JSON 填充嵌套视图模型?有什么我遗漏的或者 MVC 不能做到这一点的吗?

【问题讨论】:

    标签: asp.net-mvc json viewmodel


    【解决方案1】:

    如果您希望 MVC 模型绑定器在使用 $.ajax 发送数据时正确解析您的集合,您需要做两件事:

    • contentType 设置为'application/json'
    • 你的data 应该保存 JSON 所以JSON.stringify 数据

    所以这是正确的用法,然后可以由模型绑定器解析:

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

    【讨论】:

      猜你喜欢
      • 2020-09-29
      • 2019-08-04
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-17
      • 2017-04-13
      相关资源
      最近更新 更多