【发布时间】:2017-06-20 20:36:58
【问题描述】:
我需要数据绑定一个 JSON 对象,其中接收模型具有另一个模型的列表。示例:
public class User
{
public string FirstName;
public string LastName;
public List<Friend> Friends;
}
朋友等级:
public class Friend
{
public string NickName;
public string FirstMetLocation;
}
我需要构建一个 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
};
最终生成 JSON 如下:
{"FirstName":"Joe","LastName":"Somebody","Friends":[{"NickName":"Bongos","FirstMetLocation":"That place"}]}
然后我通过 AJAX POST 将其传递给我的操作:
$.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 属性,但List<Friend> 为空。当我将其剥离为仅传入 List<Friend> 时,它工作正常。 JSON 看起来像这样:
{"Friends":[{"NickName":"Bongos","FirstMetLocation":"That place"}]}
我错过了什么吗?
【问题讨论】:
标签: c# asp.net json asp.net-mvc data-binding