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!

2
  • 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. Commented Mar 7, 2016 at 17:46
  • If your wanting to dynamically add collection items, refer the answers here and here 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) Commented Mar 8, 2016 at 0:55

1 Answer 1

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="text" name="[0].Name" />
<input type="number" name="[1].Age" />
<input type="text" name="[1].Name" />
Sign up to request clarification or add additional context in comments.

2 Comments

As pretty much a link-only answer, I think this should be a comment.
This seems like the best solution, but I'll need to find an efficient way of naming the new input boxes to fit the index of the List.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.