繁体   English   中英

如何使用ajax将嵌套的json对象发送到mvc控制器

[英]How to send nested json object to mvc controller using ajax

我正在研究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属性为null。 任何人都可以告诉我我错过了什么?

你需要将你的字符串格式化为正确的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>

然后输出将是 -

在此输入图像描述

在创建PersonModel实例后,创建ContactModel的实例并将其分配给PersonModel下的联系人。 如果需要任何澄清,请告诉我

如果你使用@html helper属性,那么form.serialize()方法将绑定所有属性,否则如果你使用像<input>这样的html元素,则将它们的name属性赋值为model属性。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM