0

Within my view I need multiple input boxes for a dynamic number of values. For example, if I have a dynamic amount of input boxes (shown here http://jsfiddle.net/skip405/9sX6X/6/). How would I pass all these values through to my controller?

At the moment, I have one input box in my view, set up like so:

<div class="col-md-10">
    @Html.TextBoxFor(m => m.StudentName, new { @class = "form-control", @id = "current", @name = "content" })
</div>

My model defines StudentName as such:

[Required]
[Display(Name = "Student name")]
public string StudentName { get; set; }

My first thought would be to set up an array within the model and store each of the data items within it, although I don't have the expertise in either ASP.NET or C# to do this.

Thanks in advance!

tereško
  • 58,060
  • 25
  • 98
  • 150
Constantly Confused
  • 595
  • 4
  • 10
  • 24
  • Not sure what your question is here, also you might add the asp.net-mvc tag as it looks like you're using ASP.NET MVC. – CodingGorilla Mar 07 '16 at 17:46
  • If your wanting to dynamically add collection items, refer the answers [here](http://stackoverflow.com/questions/29161481/post-a-form-array-without-successful/29161796#29161796) and [here](http://stackoverflow.com/questions/29837547/set-class-validation-for-dynamic-textbox-in-a-table/29838689#29838689) for some examples. And do not attempt to set the `name` attribute when using the `HtmlHelper` methods (not that its working anyway) and use `new { id = "" }` to remove the `id` attribute otherwise you will have dulplicate `id` attributes (which is invalid html) –  Mar 08 '16 at 00:55

1 Answers1

2

The process of converting data from request to the action input parameters in the controller is called Model Binding. A lot of flexibility is implemented here, see Model Binding To A List

The basic idea is that if you have several inputs with the same name, they can be bound to a List<string>.

more complex scenarios are possible as well: if you have a like

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

and an action method:

public ActionResult DoSomething(List<Person> people)
{
     //do something
}

the input fields can be like this:

<input type="number" name="[0].Age" />
<input type="number" name="[0].Name" />
<input type="number" name="[1].Age" />
<input type="number" name="[1].Name" />
Alireza
  • 5,421
  • 5
  • 34
  • 67