Posting A String Array

风格不统一 提交于 2019-12-18 15:34:47

问题


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


回答1:


Posting a Collection of Primitives With ASP.NET MVC

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);
}

Posting a Collection of More Complex Objects

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
}


来源:https://stackoverflow.com/questions/28325456/posting-a-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!