我将mvc对象绑定到哪种javascript数组?

时间:2012-05-27 19:26:53

标签: asp.net-mvc-3 asp.net-ajax

我使用[int,bool]填充数组:

$.each(ownedChecked, function (key, val) {
    /*code to set id as int and paintedTrue as bool*/
    ownedIDs.push([id,paintedTrue]);
});

我创建了一个将被字符串化的var:

var saveData = { OwnedListEntryIDs:ownedIDs };

//send data
$.ajax({
    url: '/ListEntry/OwnedModels',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(saveData),
    success: function (data) { alert('Update success: ' + data); },
    failure: function (data) { alert('Update failed: ' + data); }
});

这是ViewModel:

public class OwnedPaintedSave
{
    //collection contains a ListEntryID and a bool indicating whether it is painted or not
    public Dictionary<int,bool> OwnedListEntryIDs { get; set; }
}

一旦进入控制器方法,ModelState.Isvalid传递和代码到达foreach循环,但模型总是为NULL:

[HttpPost]
public JsonResult OwnedModels(OwnedPaintedSave models)
{
    if (ModelState.IsValid)
    {
        foreach (var id in models.OwnedListEntryIDs)
        { }
    }
}

我尝试在$ .ajax方法中设置传统:true,但同样的问题。我猜测ViewModel中的Dictionary不是我需要绑定的,但我不确定它应该是什么。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

我为OwnedPaintedSave对象提供了两个int []属性,一个用于OwnedID,一个用于PaintedID。

答案 1 :(得分:0)

我认为问题出在你的控制器上。您正在传递var saveData = { OwnedListEntryIDs:ownedIDs };(基本上是Dictionary<int, bool> - 是吗?)作为您的数据,但操作结果中的参数是OwnedPaintedSave

类型

我认为如果您将控制器参数更改为Dictionary<int, bool> ownedListEntryIDs并且不对javascript对象进行字符串化,则该框架非常聪明,可以对您的对象进行序列化和反序列化。所以你会有这个......

var saveData = { OwnedListEntryIDs:ownedIDs };

//send data
$.ajax({
    url: '/ListEntry/OwnedModels',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: saveData,
    success: function (data) { alert('Update success: ' + data); },
    failure: function (data) { alert('Update failed: ' + data); }
});

然后在你的控制器中......

[HttpPost]
public JsonResult OwnedModels(Dictionary<int, bool> ownedListEntryIDs)
{
    if (ModelState.IsValid)
    {
        foreach (var id in ownedListEntryIDs)
        { }
    }
}