开发者

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

开发者 https://www.devze.com 2023-01-06 23:26 出处:网络
I have an action that depends on a list of integers.My first instinct was to simply declare the action with a List.

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 kno开发者_如何学运维w 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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消