如何将字典作为参数传递给jQuery/Ajax的ActionResult方法?

Chr*_*ann 11 ajax asp.net-mvc jquery actionresult

我正在使用jQuery在ASP.NET MVC中使用Http Post进行Ajax调用.我希望能够传递一个价值词典.

我能想到的最接近的事情是传入一个多维的字符串数组,但实际传递给ActionResult方法的结果是一个包含"key/value"对的字符串连接的单维字符串数组.

例如,下面"values"数组中的第一项包含以下值:

"id,200"
Run Code Online (Sandbox Code Playgroud)

这是我的ActionResult方法的一个例子:

public ActionResult AddItems(string[] values)
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

这是我如何从jQuery调用方法的示例:

$.post("/Controller/AddItems",
    {
        values: [
            ["id", "200"],
            ["FirstName", "Chris"],
            ["DynamicItem1", "Some Value"],
            ["DynamicItem2", "Some Other Value"]
        ]
    },
    function(data) { },
    "json");
Run Code Online (Sandbox Code Playgroud)

有谁知道如何将一个Dictionary对象从jQuery传递给ActionResult方法而不是一个数组?

我真的想定义我的ActionResult像这样:

public ActionResult AddItems(Dictionary<string, object> values)
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

更新:我尝试在值中传入一个逗号,它基本上只是使得无法使用字符串解析实际解析键/值对.

通过这个:

values: [
    ["id", "200,300"],
    ["FirstName", "Chris"]
]
Run Code Online (Sandbox Code Playgroud)

结果如下:

values[0] = "id,200,300";
values[1] = "FirstName,Chris";
Run Code Online (Sandbox Code Playgroud)

Chr*_*ann 10

最后我发现了!! 感谢大家的建议!我终于找到了最好的解决方案是通过Http Post传递JSON并使用自定义ModelBinder将JSON转换为Dictionary.我在我的解决方案中做的一件事是创建一个继承自Dictionary的JsonDictionary对象,以便我可以将自定义ModelBinder附加到JsonDictionary类型,如果我稍后使用Dictionary作为ActionResult参数,它将来不会引起任何冲突与JSON不同的目的.

这是最终的ActionResult方法:

public ActionResult AddItems([Bind(Include="values")] JsonDictionary values)
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)

和jQuery"$ .post"调用:

$.post("/Controller/AddItems",
{
    values: Sys.Serialization.JavaScriptSerializer.serialize(
            {
                id: 200,
                "name": "Chris"
            }
        )
},
function(data) { },
"json");
Run Code Online (Sandbox Code Playgroud)

然后需要注册JsonDictionaryModelBinder,我将它添加到Global.asax.cs中的Application_Start方法:

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(JsonDictionary), new JsonDictionaryModelBinder());
}
Run Code Online (Sandbox Code Playgroud)

最后,这里是我创建的JsonDictionaryModelBinder对象和JsonDictionary对象:

public class JsonDictionary : Dictionary<string, object>
{
    public JsonDictionary() { }

    public void Add(JsonDictionary jsonDictionary)
    {
        if (jsonDictionary != null)
        {
            foreach (var k in jsonDictionary.Keys)
            {
                this.Add(k, jsonDictionary[k]);
            }
        }
    }
}

public class JsonDictionaryModelBinder : IModelBinder
{
    #region IModelBinder Members

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.Model == null) { bindingContext.Model = new JsonDictionary(); }
        var model = bindingContext.Model as JsonDictionary;

        if (bindingContext.ModelType == typeof(JsonDictionary))
        {
            // Deserialize each form/querystring item specified in the "includeProperties"
            // parameter that was passed to the "UpdateModel" method call

            // Check/Add Form Collection
            this.addRequestValues(
                model,
                controllerContext.RequestContext.HttpContext.Request.Form,
                controllerContext, bindingContext);

            // Check/Add QueryString Collection
            this.addRequestValues(
                model,
                controllerContext.RequestContext.HttpContext.Request.QueryString,
                controllerContext, bindingContext);
        }

        return model;
    }

    #endregion

    private void addRequestValues(JsonDictionary model, NameValueCollection nameValueCollection, ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        foreach (string key in nameValueCollection.Keys)
        {
            if (bindingContext.PropertyFilter(key))
            {
                var jsonText = nameValueCollection[key];
                var newModel = deserializeJson(jsonText);
                // Add the new JSON key/value pairs to the Model
                model.Add(newModel);
            }
        }
    }

    private JsonDictionary deserializeJson(string json)
    {
        // Must Reference "System.Web.Extensions" in order to use the JavaScriptSerializer
        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Deserialize<JsonDictionary>(json);
    }
}
Run Code Online (Sandbox Code Playgroud)