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?
Best Answer
I modified my response to include the code for a test app I did.
Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).
First the javascript:
And here's the code in my controller class:
When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!