【问题标题】:How to send nested json object to mvc controller using ajax如何使用 ajax 将嵌套的 json 对象发送到 mvc 控制器
【发布时间】:2014-02-28 07:40:07
【问题描述】:

我正在开发一个 ASP.NET MVC 应用程序。我在 c# 中有以下视图模型:

public class ContactModel
{
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

public class PersonModel
{
    public ContactModel Contact;

    public PersonModel()
    {
        Contact = new ContactModel();
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Profession { get; set; }
}

现在我在客户端有相同的 json 模型,我想发布到服务器。我正在使用以下 jquery ajax:

$.ajax({
    url: "address to controller",
    type: "post",
    data: JSON.stringify(data),
    contentType: "application/json",
    success: function () {
        alert("data saved successfully");
    }
});

但只有 PersonModel 属性被映射,但 Contact 属性为空。谁能告诉我我错过了什么??

【问题讨论】:

  • data的内容是什么?
  • 数据变量的内容是"{"Contact":{"Address":"xyz","City":"xyz","State":"xyz"},"FirstName":"xyz","LastName":"xyz","Profession":"87"}"
  • 我发现了问题,问题是我没有给集合;访问我的PersonModel 中的属性Contact,因此默认模型绑定器无法将新对象设置为Contact 属性。我刚刚为Contact 属性添加了{ get; set; },问题解决了!

标签: c# javascript jquery asp.net-mvc


【解决方案1】:

创建一个ContactModel实例,创​​建完PersonModel实例后,将其分配给PersonModel下的contact。 如果需要任何澄清,请告诉我

【讨论】:

  • 我不明白你的建议请澄清??
【解决方案2】:

您需要将字符串格式化为正确的 json -

如果你的模特是 -

public class ContactModel
{
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}

public class PersonModel
{
    public ContactModel Contact { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Profession { get; set; }
}

那你的AJAX Post应该是这样的——

<script>
    $(function () {
        $('#click1').click(function (e) {

            var studentData = {
                "FirstName": "Rami",
                "LastName": "Vemula" ,
                "Contact": { "City": "Hyd"}
            };

            $.ajax({
                url: "@Url.Action("Submit")",
                type: "POST",
                data: JSON.stringify(studentData),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (response) {
                    alert(response.responseText);
            },
                success: function (response) {
                    alert(response);
                }
            });

        });
    });
</script>

然后输出将是 -

【讨论】:

    【解决方案3】:

    如果您使用@html 属性助手,那么form.serialize() 方法将绑定所有属性,否则如果您使用像&lt;input&gt; 这样的html 元素,则将它们的名称属性指定为与模型属性相同。

    <input type="text" name="Contact.FirstName" value="@Model.Contact.FirstName"/>
    

    【讨论】:

      猜你喜欢
      • 2011-08-19
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多