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

后端 未结 6 1518
无人共我
无人共我 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条回答
  •  攒了一身酷
    2020-11-30 05:47

    DefaultModelBinder is able to bind your POST to array or dictionary. For example:

    for arrays:

    public ActionResult AddItems(string[] values)
    
    $.post("/Controller/AddItems", { values: "values[0]=200&values[1]=300" },
        function(data) { }, "json");
    

    or:

    $.post("/Controller/AddItems", { values: "values=200&values=300" },
        function(data) { }, "json");
    

    for dictionaries:

    public ActionResult AddItems(Dictionary values)
    
    $.post("/Controller/AddItems", {
        values: "values[0].Key=value0&values[0].Value=200&values[1].Key=value1&values[1].Value=300" }, function(data) { }, "json");
    

    UPDATED:

    If your values are in HTML inputs then in jQuery you can do something like this:

    var postData = $('input#id1, input#id2, ..., input#idN").serialize();
    // or
    var postData = $('input.classOfYourInputs").serialize();
    
    $.post("/Controller/AddItems", { values: postData }, function(data) { }, "json");
    

    UPDATED:

    Also check this: Scott Hanselman's ComputerZen.com - ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries

提交回复
热议问题