DefaultModelBinder无法将作为JSON对象传递给操作的.NET字典对象反序列化? [英] DefaultModelBinder cannot deserialize .NET Dictionary object passed to an action as a JSON object?
问题描述
我有一堂很简单的课:
public class FilterItem
{
public Dictionary<string, string> ItemsDictionary { get; set; }
public FilterItem()
{
ItemsDictionary = new Dictionary<string, string>();
}
}
我想在客户端的字典中填充数据,然后将其作为JSON对象传递给我的控制器操作.但是,无论我在客户端上尝试什么,DefaultModelBinder似乎都无法将其反序列化.
I want to populate the data in the dictionary on the client and then pass it to my controller action as a JSON object. However no matter what I try on the client, the DefaultModelBinder does not seem to be able to deserialize it.
这是一个示例JavaScript代码,用于调用我的操作:
Here is an example javascript code to call my action:
var simpleDictionary = {"ItemsDictionary": {"1": "5", "2": "7"}};
$.ajax({ cache: false, type: "POST", data: JSON.stringify(simpleDictionary),
contentType: "application/json; charset=utf-8",
url: "/Catalog7Spikes/GetFilteredProductsJson", success: function (data) {...});
这是我的操作方法的简化版本:
And here is a simplified version of my action method:
[HttpPost]
public ActionResult GetFilteredProductsJson(FilterItem filterItem)
{
ProductsModel productsModel = new ProductsModel();
return View("SevenSpikes.Nop.UI.Views.Products", productsModel);
}
请注意相反的方法.当作为JsonResult传递时,FilterItem对象已成功序列化并作为JSON对象传递给客户端.但是,尝试以相反的方式行不通.
Please note that the opposite works. When passed as a JsonResult the FilterItem object is successfully serialized and passed as a JSON object to the client. However trying to go the other way round does not work.
I read the ticket on Connect and thought that the work around would work but it does not.
使用ASP.NET MVC 3中的DefaultModelBinder可以完全反序列化.NET词典吗?
Is it possible at all to deserialize a .NET dictionary using the DefaultModelBinder in ASP.NET MVC 3?
推荐答案
汉塞尔曼(Hanselman)谈到:
Hanselman talks about this:
DefaultModelBinder
期望字典的语法不尽人意.尝试使用这种语法:
The DefaultModelBinder
expects some less-than-optimal syntax for dictionaries. Try using this kind of syntax:
{
"dictionary[0]":{"Key":"a", "Value":"b"},
"dictionary[1]":{"Key":"b", "Value":"b"}
}
有点笨重,但可以绑定.以下方法也可以,但是我个人更喜欢上面的方法;它更短.
It's kind of bulky but it binds. The following works as well, but I personally prefer the above; it's shorter.
{
"dictionary[0].Key":"a",
"dictionary[0].Value":"b",
"dictionary[1].Key":"b"
"dictionary[1].Value":"b"
}
这篇关于DefaultModelBinder无法将作为JSON对象传递给操作的.NET字典对象反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!