有没有办法传递这个javascript对象
Object { 35=true, 179=true, 181=true}
作为控制器动作
Dictionary<int, bool>
我检查了以下方法:
var remoteUrl = "@Url.Action("UpdateProjectStructureSelection")" + "?tlpId=@Model.TopLevelProjectId";
$.post(remoteUrl, mapSiteSelectionChoices, function(callbackResult) {
alert(callbackResult);
});
和
var remoteUrl = "@Url.Action("UpdateProjectStructureSelection")" + "?tlpId=@Model.TopLevelProjectId";
$.post(remoteUrl, { values : mapSiteSelectionChoices }, function(callbackResult) {
alert(callbackResult);
});
然而在两种情况下
public ActionResult UpdateProjectStructureSelection(int tlpId, Dictionary<int, bool> values)
已调用,但值为空。
由于我已经将更复杂的类型转换为控制器动作而没有编写自定义模型绑定器,我一直在想我是否只是在这里做错了。
自定义模型绑定器是将字体作为字典的唯一方法吗? (除了在客户端使用JsonConvert + stringify之外)
添加(这有效,但我喜欢避免额外的代码):
public ActionResult UpdateProjectStructureSelection(int tlpId, string values)
{
var dict = JsonConvert.DeserializeObject<Dictionary<int, bool>>(values);
}
答案 0 :(得分:3)
不使用该格式的对象。它需要采用以下格式才能被DefaultModelBinder
var data = { 'dict[0].key': '35', 'dict[0].value': 'True', 'dict[1].key': '179', 'values[1].value': 'True', dict[0].key': '8', 'dict[0].value': 'True' };
$.post(remoteUrl, data, function(callbackResult) {
和控制器
public ActionResult UpdateProjectStructureSelection(Dictionary<int, bool> dict)
如您所述,另一种选择是使用自定义ModelBinder
,例如this answer