简体   繁体   中英

How to send nested json object to mvc controller using ajax

I am working on an ASP.NET MVC application. I have the following view model in 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; }
}

Now i have the same json model at client side which i want to post to server. I am using following jquery ajax:

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

But only PersonModel properties are get mapped but Contact properties are null. Can anybody please tell me what i am missing??

You need for format your string to proper json -

Say if you model is -

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; }
}

Then you AJAX Post should be like this -

<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>

Then output is going to be -

在此输入图像描述

Create a instance of ContactModel and assign it to contact under PersonModel after creating instance of PersonModel. Please let me know in case of any clarification needed

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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