Reputation: 12321
How can I handle an array of input
For example I have in my view:
<input type="text" name="listStrings[0]" /><br />
<input type="text" name="listStrings[1]" /><br />
<input type="text" name="listStrings[2]" /><br />
In my control I try to get the values like:
[HttpPost]
public ActionResult testMultiple(string[] listStrings)
{
viewModel.listStrings = listStrings;
return View(viewModel);
}
On debugging I can see listStrings
is null
every time.
Why is it null and how can I get the values of the input array
Upvotes: 9
Views: 8102
Reputation: 15429
To post a collection of primitives the inputs just have to have the same name. That way when you post the form the request's body will look like
listStrings=a&listStrings=b&listStrings=c
MVC will know that since these parameters have the same name they should be converted to a collection.
So, change your form to look like this
<input type="text" name="listStrings" /><br />
<input type="text" name="listStrings" /><br />
<input type="text" name="listStrings" /><br />
I would also recommend changing the parameter type in your controller method to be an ICollection<string>
instead of a string[]
. So your controller would look like this:
[HttpPost]
public ActionResult testMultiple(ICollection<string> listStrings)
{
viewModel.listStrings = listStrings;
return View(viewModel);
}
Now, if you wanted to post a collection of more complex objects, say an ICollection<Person>
where your definition of the Person
class was
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
then the naming convention you used in your original form would come into play. Since you will need multiple inputs representing different properties to post the whole object now, just naming the inputs with the same name won't make sense. You will have to specify which object and which property an input represents in the name. For this you will use the naming convention collectionName[index].PropertyName
.
For instance an input for the Age
property of a Person
might have a name like people[0].Age
.
A form used to submit an ICollection<Person>
in this case would look like:
<form method="post" action="/people/CreatePeople">
<input type="text" name="people[0].Name" />
<input type="text" name="people[0].Age" />
<input type="text" name="people[1].Name" />
<input type="text" name="people[1].Age" />
<button type="submit">submit</button>
</form>
The method expecting the request would look something like this:
[HttpPost]
public ActionResult CreatePeople(ICollection<Person> people)
{
//Do something with the people collection
}
Upvotes: 20