<...">

Posting a String Array

How can I process an input array

For example, I have in my opinion:

<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 am trying to get values ​​like:

 [HttpPost] public ActionResult testMultiple(string[] listStrings) { viewModel.listStrings = listStrings; return View(viewModel); } 

When debugging, I can see listStrings null every time.

Why is it null and how can I get input array values

+7
arrays asp.net-mvc asp.net-mvc-5
source share
1 answer

Publishing a collection of primitives using ASP.NET MVC

To publish a collection of primitives, the inputs must have the same name. Thus, when you submit the form, the request body will look like

 listStrings=a&listStrings=b&listStrings=c 

MVC will know that since these parameters have the same name, they must be converted to a collection.

So, change the shape 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 type of the parameter in your controller method as ICollection<string> instead of string[] . So your controller will look like this:

 [HttpPost] public ActionResult testMultiple(ICollection<string> listStrings) { viewModel.listStrings = listStrings; return View(viewModel); } 

Publish a collection of more complex objects

Now, if you want to publish a collection of more complex objects, say ICollection<Person> , where your Person class definition was

 public class Person { public string Name { get; set; } public int Age { get; set; } } 

then the naming convention that you used in the original form will come into play. Since you will need several inputs representing different properties in order to publish the whole object now, it just makes no sense to name the inputs with the same name. You will need to specify which object and which property is entered in the name. You will use the collectionName[index].PropertyName .

For example, the entry for the Age property of the Person object may be of the type people[0].Age .

The form used to submit the ICollection<Person> in this case will look like this:

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

A method waiting for a request will look something like this:

 [HttpPost] public ActionResult CreatePeople(ICollection<Person> people) { //Do something with the people collection } 
+15
source share

All Articles