Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a list of integers to an MVC action?

I have an action that depends on a list of integers. My first instinct was to simply declare the action with a List.

I tried declaring the action in the controller as:

public ActionResult EditMultiple(List<int> ids)

and in my View call like so:

<%= Html.ActionLink("EditMultiple", "EditMultiple", new { ids = new List<int> {2, 2, 2} })%>

Although it compiles the List is empty when I put a breakpoint in the action. Anybody know why or have an alternate approach?

Adding more detail about the scenario:

I'm trying to "Edit" multiple entities at the same time. I'm already at the point where I have an application that allows me to create/edit/view information about books in a library. I have a partial view that allows the user to edit information about a single book and save it to the database.

Now I'd like to create a View which allows the user to edit the information about multiple books with a single submit button. I've created an action EditMultiple which just renders the partial for each book (my model for this view is List) and adds the submit button afterwards.

like image 353
Justin Avatar asked Jul 08 '10 22:07

Justin


2 Answers

Yes. The default model binder can bind "ids" to any ICollection. But you have to submit multiple parameters with the same name. That eliminates using the helper method "ActionLink". You can use url helper Action and append the ids to the link like so:

<a href="<%= Url.Action("CreateMultiple")%>?ids=2&ids=1&ids=3">Test link</a>

Here's the link from Haack's block.

like image 92
BC. Avatar answered Nov 12 '22 10:11

BC.


I dont think

new List<int> {2, 2, 2}

gets properly converted into an POST that is bindable, you want to send

Ids=1&Ids=2&Ids=3

a comma separate list may also work, im not sure, i don't use the crappy default modelbinder.

Why are you doing that anyway? I hope thats pseudocode for something else...

like image 20
Andrew Bullock Avatar answered Nov 12 '22 10:11

Andrew Bullock