views:

5543

answers:

3

Hi there,

I am creating a small app to teach myself ASP.NET MVC and JQuery, and one of the pages is a list of items in which some can be selected. Then I would like to press a button and send a List (or something equivalent) to my controller containing the ids of the items that were selected, using JQuery's Post function.

I managed to get an array with the ids of the elements that were selected, and now I want to post that. One way I could do this is to have a dummy form in my page, with a hidden value, and then set the hidden value with the selected items, and post that form; this looks crufty, though.

Is there a cleaner way to achieve this, by sending the array directly to the controller? I've tried a few different things but it looks like the controller can't map the data it's receiving. Here's the code so far:

  function generateList(selectedValues) {
     var s = {
        values: selectedValues //selectedValues is an array of string
     };
     $.post("/Home/GenerateList", $.toJSON(s), function() { alert("back") }, "json");
  }

And then my Controller looks like this

    public ActionResult GenerateList(List<string> values)
    {
        //do something
    }

All I managed to get is a "null" in the controller parameter...

Any tips?

+4  A: 

Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.

You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.

Craig Stuntz
Thanks. Updated url is: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Zidad
+10  A: 

Hey rod-

I modified my response to include the code for a test app I did. First the javascript:

function test()
{
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };

    $.post("/Home/SaveList",
    postData,
    function(data){
        alert(data.Result);
    }, "json");
}

And here's the code in my controller class:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!

MrDustpan
It worked, thanks a lot :)
rodbv
+9  A: 

FYI: JQuery changed the way they serialize post data.

http://forum.jquery.com/topic/nested-param-serialization

You have to set the 'Traditional' setting to true, other wise

{Values:["1","2","3"]}

will come out as

Values[]=1&Values[]=2&Values[]=3

instead of

Values=1&Values=2&Values=3

DustinDavis
Thanks! I was pretty confused until I scrolled down to this!
Chris