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
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.