Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net-mvc

Can i use List or something?

like image 750
Neir0 Avatar asked Aug 10 '10 15:08

Neir0


People also ask

What is index action method in MVC?

By default, the Index() method is a default action method for any controller, as per configured default root, as shown below. Default Route. routes. MapRoute( name: "Default", url: "{controller}/{action}/{id}/{name}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.


2 Answers

You need to pass them to your action via adding each integer to your POST or GET querystring like so:

myints=1&myints=4&myints=6

Then in your action you will have the following action

public ActionResult Blah(List<int> myints)

MVC will then populate the list with 1,4, and 6

One thing to be aware of. Your query string CANNOT have brackets in them. Sometimes when the javascript lists are formed your query string will look like this:

myints[]=1&myints[]=4&myints[]=6

This will cause your List to be null (or have a count of zero). The brackets must not be there for MVC to bind your model correctly.

like image 105
KallDrexx Avatar answered Oct 10 '22 20:10

KallDrexx


If you are trying to send the list from some interface item (like, a table), you can just set their name attribute in the HTML to: CollectionName[Index] for example:

<input id="IntList_0_" name="IntList[0]" type="text" value="1" />
<input id="IntList_1_" name="IntList[1]" type="text" value="2" />

And

public ActionResult DoSomething(List<int> IntList) {
}

The IntList parameter wil receive a list containing 1 and 2 in that order

like image 27
Tejo Avatar answered Oct 10 '22 20:10

Tejo