How to send nested json object to mvc controller using ajax

后端 未结 3 986
太阳男子
太阳男子 2020-12-22 04:20

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


        
相关标签:
3条回答
  • 2020-12-22 04:58

    If you are using @html helper for properties then form.serialize() method will bind all the properties otherwise if you are using html elements like <input> the assign their name property same as model property.

    <input type="text" name="Contact.FirstName" value="@Model.Contact.FirstName"/>
    
    0 讨论(0)
  • 2020-12-22 05:00

    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

    0 讨论(0)
  • 2020-12-22 05:19

    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

    0 讨论(0)
提交回复
热议问题