【问题标题】:ASP.NET MVC 3 Json Model Binding with 3 levels objectASP.NET MVC 3 Json 模型绑定与 3 级对象
【发布时间】:2011-11-02 20:26:25
【问题描述】:

为什么 json 中的 3 级嵌套模型绑定不起作用?

使用 2 个级别进行测试,比如在 LevelTwo 上添加一个字符串属性,可以,但是 3 个级别不行吗?这是设计使然、错误还是我遗漏了什么?

客户端 jQuery 发布:

    $.ajax({
        url: "MyController/MyAction",
        dataType: "json",
        type: "POST",
        cache: false,
        data: {
            Level1: {
                Level2: {
                    StringValue: "Test"
                }
            }
        }
    });

服务器端模型:

public class MyForm
{
    public LevelOne Level1 { get; set; }
}

public class LevelOne
{
    public LevelTwo Level2 { get; set; }
}

public class LevelTwo
{
    public string StringValue { get; set; }
}

【问题讨论】:

    标签: json asp.net-mvc-3 model-binding


    【解决方案1】:

    为什么 json 中的 3 级嵌套模型绑定不起作用

    您没有向服务器发送任何 JSON。如果你想发送 JSON 请求,方法如下:

    $.ajax({
        url: "MyController/MyAction",
        contentType: 'application/json; charset=utf-8',
        dataType: "json",
        type: "POST",
        cache: false,
        data: JSON.stringify({ 
            Level1: { 
                Level2: { 
                    StringValue: "Test" 
                } 
            } 
        })
    });
    

    JSON.stringify 方法将 javascript 文字序列化为 JSON 字符串。它是在现代浏览器中原生构建的。如果您需要支持旧版浏览器,您可以将json2.js 脚本添加到您的页面中。

    【讨论】:

    • 噢!谢谢!我认为 dataType: "json" 就是所需要的。你知道,假设是一切之母......
    • @MatteS, dataType: 'json' 表示响应内容类型,而不是请求。此外,如果您的服务器向 application/json 发送正确的 Content-Type 响应标头,您甚至不需要它,因为 jQuery 会自动推断它。您可以在 ajax 请求中省略此参数。
    • 是的。这让我回想起为什么在我们的代码库中首先添加了 dataType 选项,并且可能值得注意的是它添加了标题“Accept:application/json, text/javascript, /;"到请求,这就是我们的错误处理逻辑喜欢的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多