Wat*_* v2 2 asp.net-mvc jquery model-binding
我的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; }
}
Run Code Online (Sandbox Code Playgroud)
从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 };
}
Run Code Online (Sandbox Code Playgroud)
......等等,将值变为变量
请注意,我送什么应该进入Person.Friends时,IList<T>作为一个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
});
Run Code Online (Sandbox Code Playgroud)
在我的控制器中,只要我有一个FormCollection接收数据,我获取所有数据,但我想绑定到强类型的Person对象,所以如果我更改我的控制器定义:
[HttpPost]
public ActionResult JsonCreateNew(FromCollection person)
{
// I get all the data in the person.AllKeys property
return new EmptyResult();
}
Run Code Online (Sandbox Code Playgroud)
至:
[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();
}
Run Code Online (Sandbox Code Playgroud)
我仍然得到我的所有数据,但我真的仍然关心IList<Friend>.
它在Person对象中被接收为具有正确数量的Friends具有正确属性名称(Name和Id)的对象的数组,但是每个Friend对象的两个属性的值都是null0,即使在有值被发送的情况下也未初始化.客户.
请帮忙.
如果colection属性名称以它未绑定的类型名称开头,则MVC中有一个错误拒绝修复它.更改
public IList<Friend> Friends { get; set; }
Run Code Online (Sandbox Code Playgroud)
至:
public IList<Friend> Biscuits { get; set; }
Run Code Online (Sandbox Code Playgroud)
只是暂时的.它会工作.
| 归档时间: |
|
| 查看次数: |
14623 次 |
| 最近记录: |