我在我的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
中的内容,即一个JavaScript数组,其中数组的每个元素都是一个关联列表,其属性与服务器端的Friend
类相同。
这是我的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
和 Id
),但每个 Friend
对象的两个属性值(Name
和 Id
)都是 null
或 0,即使客户端发送了值也不会初始化。请帮忙。