Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - 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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 -

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...