我的 MVC 代码中有一个服务器端对象,如下所示:
class Person
{
public long Id { get; set; }
public string Name { get; set; }
public IList<Friend> Friends { get; set; }
}
class Friend
{
public long Id { get; set; }
public string Name { get; set; }
}
我从 jQuery 客户端发出 ajax 请求并发送以下数据(为了便于阅读而引入换行符):
var personId = $(...
var personName = $(...
var friends = []; // array of associative arrays
for (var i = 0; i < _friends.length; i++) // _friends is is a global array object and is different from friends below
{
var friendId = $(...
var friendName = $(...)
friends[i] = { 'Id' : friendId, 'Name' : friendName };
}
...等等将值放入变量中
请注意我正在发送应填写的内容Person.Friends
, the IList<T>
作为 JavaScript 数组,其中数组的每个元素都是一个关联列表,其属性与服务器端类似Friend
class.
这是我的 ajax 请求:
$.ajax('/Strings/JsonCreateNew',
{
cache: false, async: false, type: 'POST',
data: {
'Id' : personId,
'Name' : personName,
'Friends' : friends},
dataType: 'json',
error: SaveNewFriendClientSideHandler.OnError,
success: SaveNewFriendClientSideHandler.OnSuccess
});
在我的控制器中,只要我有FormCollection
为了接收数据,我获取了所有数据,但我想绑定到强类型的 Person 对象,因此如果我将控制器定义更改为:
[HttpPost]
public ActionResult JsonCreateNew(FromCollection person)
{
// I get all the data in the person.AllKeys property
return new EmptyResult();
}
to:
[HttpPost]
public ActionResult JsonCreateNew(Person person)
{
// the default ASP.NET MVC model binder isn't able to bind to this
// in fact, the routing module does not even route the request to this
// action, so this action never gets fired.
return new EmptyResult();
}
我仍然得到了所有数据,但我真的仍然担心IList<Friend>
.
它被接收在Person
对象作为具有正确数量的数组Friends
具有正确属性名称的对象(Name
and Id
)但是每个属性的值Friend
对象是null
或 0,即即使客户端发送了值也不初始化。
请帮忙。