Asked by:
How to pass collections to ActionResult methods

Question
-
User1314407993 posted
I'm generating a List<int> collection that I want to pass into a Controller method, but it's showing 0 elements when it arrives. I've checked the variable state right before it is sent (even with the same controller), and the collection has 433 elements. Just to check, I changed it to just a regular int variable, and it worked just fine.
How do I pass a collection and have it retain its values? I don't understand why the values are being dropped.
Tuesday, July 12, 2011 11:16 AM
All replies
-
User1904378495 posted
Where are you generating the List<int> and how are you passing it to the controller action method?
If you are trying to pass a collection from view, then take a look at this blog post on how to model bind to a list
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspxTuesday, July 12, 2011 11:34 AM -
User915317108 posted
Can i see some code for the controller method and the view? Maybe i could help!
Kelv
Tuesday, July 12, 2011 11:36 AM -
User1314407993 posted
There's not a lot of code to post, and the issue doesn't include any interaction with a View. Basically I was trying to do some work in a base Controller, and then pass a list of integers or user-defined objects to the Controller that would generate the View. However, the collection would be empty in the Controller that it was passed to. I checked its state immediately before I passed it, and then after the method called started. Before it has values, but when passed to a Controller method it was empty. I replaced the list of integers with a single integer parameter and it passed without a problem.
Monday, July 25, 2011 4:41 PM -
User197322208 posted
. Basically I was trying to do some work in a base Controller, and then pass a list of integers or user-defined objects to the ControllerI checked its state immediately before I passed it, and then after the method called started. Before it has values, but when passed to a Controller method it was empty. I replaced the list of integers with a single integer parameter and it passed without a problem.Code, please...
Monday, July 25, 2011 5:07 PM -
User1034446946 posted
could you not pass the int's to the controller as an array so the html would be
<input type="text" name="listofints">
<input type="text" name="listofints">
<input type="text" name="listofints">
<input type="text" name="listofints">notice all the input boxes have the same name
then in the controller have
public ActionResult Something( int[] listofints)
Monday, July 25, 2011 6:51 PM -
User1928394251 posted
hello,i hope help you.
<input type="text" id="listofints1" name="listofints" />
<input type="text" id="listofints2" name="listofints" />
public ActionResult test(FormCollection form) { var model = testmodel(); model.firstname = form["listofints1"].ToString(); model.lastname = form["listofints2"].ToString(); }Monday, December 31, 2018 5:19 AM