C# 带有对象数组的.NET MVC数据绑定JSON对象
我需要数据绑定一个JSON对象,其中接收模型有另一个模型的列表。例如:C# 带有对象数组的.NET MVC数据绑定JSON对象,c#,asp.net,json,asp.net-mvc,data-binding,C#,Asp.net,Json,Asp.net Mvc,Data Binding,我需要数据绑定一个JSON对象,其中接收模型有另一个模型的列表。例如: public class User { public string FirstName; public string LastName; public List<Friend> Friends; } 我需要构建一个JSON对象,在调用操作时将其数据绑定到用户模型 我构建JSON对象的方式如下: var friends = []; // iterate over something and
public class User
{
public string FirstName;
public string LastName;
public List<Friend> Friends;
}
我需要构建一个JSON对象,在调用操作时将其数据绑定到用户模型
我构建JSON对象的方式如下:
var friends = [];
// iterate over something and add friend object to array
friends.push({
NickName: 'Bongos',
FirstMetLocation: 'That place'
});
var user = {
FirstName: 'Joe',
LastName: 'Somebody',
Friends: friends
};
{"Friends":[{"NickName":"Bongos","FirstMetLocation":"That place"}]}
最终生成JSON,如下所示:
{"FirstName":"Joe","LastName":"Somebody","Friends":[{"NickName":"Bongos","FirstMetLocation":"That place"}]}
然后,我将通过AJAX帖子将其传递给我的操作:
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: user,
success: function (event) {
// do something
},
error: function (xhr, status, error) {
alert("You didn't do it right.");
}
});
当它开始执行操作时,用户对象会选择FirstName
和LastName
属性,但列表
为空。当我把它简化为只传递一个列表时
效果很好。JSON看起来是这样的:
var friends = [];
// iterate over something and add friend object to array
friends.push({
NickName: 'Bongos',
FirstMetLocation: 'That place'
});
var user = {
FirstName: 'Joe',
LastName: 'Somebody',
Friends: friends
};
{"Friends":[{"NickName":"Bongos","FirstMetLocation":"That place"}]}
我错过什么了吗 因为它是一个复杂的对象,所以将内容类型指定为application/json,并将数据作为字符串化的json字符串发送
$.ajax({
type: 'POST',
url: url,
contentType: 'application/json',
data: JSON.stringify(user),
success: function (event) {
// do something
},
error: function (xhr, status, error) {
alert("You didn't do it right.");
}
});
现在,ModelBinder将能够将从ajax调用发送的数据映射到相应的属性
还假设您的属性是集表
public class User
{
public string FirstName { set; get; }
public string LastName { set; get; }
public List<Friend> Friends { set; get; }
}
public class Friend
{
public string NickName { set; get; }
public string FirstMetLocation { set; get; }
}
公共类用户
{
公共字符串名{set;get;}
公共字符串LastName{set;get;}
公共列表朋友{set;get;}
}
公课朋友
{
公共字符串昵称{set;get;}
公共字符串FirstMetLocation{set;get;}
}
感谢您的回复!我会尽快试一试的。我的属性是可设置的。模型绑定器不能像我这样处理复杂对象,有什么原因吗?