How do I pass a Dictionary as a parameter to an ActionResult method from jQuery/Ajax?

后端 未结 6 1525
无人共我
无人共我 2020-11-30 05:27

I\'m using jQuery to make an Ajax call using an Http Post in ASP.NET MVC. I would like to be able to pass a Dictionary of values.

The closest thing I could think of

6条回答
  •  萌比男神i
    2020-11-30 05:54

    I don't think it's possible to pass in a Dictionary from jQuery/Ajax to an ActionResult method via an Http Post. One thing I figured out that seems to be the easiest to work with is to pass in a JSON object and then parse that out into a Dictionary.

    Here's the modified version of of the above calling "$.post" from jQuery that sends JSON as a pseudo-Dictionary:

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

    The "Sys.Serialization.JavaScriptSerializer.serialize" function is a method of the ASP.NET AJAX JavaScript library.

    Here's the modified version of the above ActionResult method:

    public ActionResult AddItems(Dictionary values)
    {
        // Must Reference "System.Web.Extensions" in order to use the JavaScriptSerializer
        var json = new System.Web.Script.Serialization.JavaScriptSerializer();
        var data = json.Deserialize>(routeValues);
    
        // do something
    }
    

    I think this makes it much easier to Unit Test by passing JSON, instead of using the Form Collection to send/retrieve the collection of key/value pairs. Also, it's easier to get working than figuring out how to build a custom IModelBinder, and a custom IModelBinder might cause issues with other ActionResult methods when this is the only one I need to do this.

提交回复
热议问题