[英]How to send nested json object to mvc controller using ajax
I am working on an ASP.NET MVC application. 我正在研究ASP.NET MVC应用程序。 I have the following view model in c#:
我在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. 现在我在客户端有相同的json模型,我想发布到服务器。 I am using following jquery ajax:
我正在使用以下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. 但只有PersonModel属性被映射,但Contact属性为null。 Can anybody please tell me what i am missing??
任何人都可以告诉我我错过了什么?
You need for format your string to proper json - 你需要将你的字符串格式化为正确的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 - 然后你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>
Then output is going to be - 然后输出将是 -
Create a instance of ContactModel and assign it to contact under PersonModel after creating instance of PersonModel. 在创建PersonModel实例后,创建ContactModel的实例并将其分配给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"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.