如何用ajax发送嵌套JSON对象到MVC控制器 [英] How to send nested json object to mvc controller using ajax
本文介绍了如何用ajax发送嵌套JSON对象到MVC控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我工作的一个ASP.NET MVC应用程序。我在C#中的以下视图模型:
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; }
}
现在我在客户端相同的JSON模式,我想发布到服务器。我使用jQuery的以下AJAX:
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");
}
});
但只有PersonModel属性被映射,但跟属性为null。任何人都可以请告诉我,我错过了什么?
But only PersonModel properties are get mapped but Contact properties are null. Can anybody please tell me what i am missing??
推荐答案
您需要格式化您的字符串适当JSON -
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; }
}
然后你AJAX帖子应该是这样的 -
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 -
这篇关于如何用ajax发送嵌套JSON对象到MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文