【问题标题】:Nested models don't bind嵌套模型不绑定
【发布时间】:2012-10-24 18:50:51
【问题描述】:

我想将 JSON 数据结构传递给 MVC (3) 控制器,将 JSON 对象转换为 C# 对象,并绑定所有属性。其中一个属性是简单类型。这是基本的模型绑定,对吧?

这是我的模型:

public class Person
{
    public string Name { get; set; }
    public JobTitle JobTitle { get; set; }
}

public class JobTitle
{
    public string Title { get; set; }
    public bool IsSenior { get; set; }
}

这是我的 Index.cshtml 页面(它发出 AJAX 请求,传入一个与“Person”类的结构匹配的 JSON 对象):

<div id="myDiv" style="border:1px solid #F00"></div>
<script type="text/javascript">
var person = { 
        Name: "Bob Smith",
        JobTitle: { 
            Title: "Developer",
            IsSenior: true
        } 
    };

$.ajax({
    url: "@Url.Action("ShowPerson", "Home")",
    data: $.param(person),
    success: function (response){
        $("#myDiv").html(response);
    },
    error: function (xhr) {
        $("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
    }
});
</script>

我的 HomeController 看起来像这样:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult ShowPerson(Person person)
    {
        return View(person);
    }
}

暂时忽略“ShowPerson.cshtml”文件,因为问题在需要之前就出现了。

在 HomeController.ShowPerson 动作中,“person.Name”属性被正确绑定,“person.JobTitle”对象(包含“Title”和“IsSenior”属性)被实例化,但仍具有“Title”的默认值= null”和“IsSenior = false”。

我确信我在过去完成了嵌套模型绑定没有问题。我错过了什么?任何人都可以解释为什么模型绑定似乎只能工作一层吗?

我已经搜索过了,似乎其他人在从表单发送数据时都遇到了绑定问题,所以也许我的 $.ajax() 请求中遗漏了一些东西?

【问题讨论】:

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


    【解决方案1】:

    好的,您需要做一些更改,

    • dataType设置为json
    • contentType设置为application/json; charset=utf-8
    • 使用JSON.stringify()

    下面是修改后的代码。 (测试

    var person = { 
        Name: "Bob Smith",
        JobTitle: { 
            Title: "Developer",
            IsSenior: true
        } 
    };
    
    var jsonData = JSON.stringify(person);
    
    $.ajax({
      url: "@Url.Action("ShowPerson", "Home")",
      data: jsonData,
      dataType: 'json',
      type: 'POST',
      contentType: "application/json; charset=utf-8",
    
      success: function (response){
        $("#myDiv").html(response);
      },
      error: function (xhr) {
        $("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
      }
    });
    

    【讨论】:

    • 行得通!我认为关键部分是设置 contentType。
    • 我以前遇到过这个问题,这也是当时的答案 - 抱歉成为一个工具。再次感谢您的帮助,亚瑟!
    【解决方案2】:

    将内容类型添加到ajax

    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    type: 'POST',
    data: $.toJSON(person);
    

    【讨论】:

    • 谢谢鸽子,几乎为我解决了这个问题,但我花了一段时间弄清楚为什么 $.toJSON 不起作用.... (stackoverflow.com/questions/7759619/…)
    • 是的,这可能有点过时了。它包含在 json2.js 中
    猜你喜欢
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    相关资源
    最近更新 更多