I’m working on a very flexible HTML form with ASP.NET MVC. I have a “Quantity” input element which dynamically creates [its value] sets of input elements later in the form.
For instance, if Quantity is set to 1, I have one set of textboxes for username, room number, and building name. But if Quantity is set to 10, ten each of those textboxes appear.
Obviously, when the data is posted back to the server, I need to correctly group each username, room, and building together, and not get them jumbled up.
It seems like the easiest way to do this would be to make every set the same:
<input type="text" name="username"/>
<input type="text" name="room"/>
<select name="building"> <!--All this x Quantity-->
<option value="TARDIS">TARDIS</option>
<option value="USS Enterprise">USS Enterprise</option>
</select>
<input type="text" name="username"/> <!--And so on...-->
And then trust that the POST string will preserve the order in which the elements are written in the HTML, thereby allowing me to say back on the server once I’ve captured these values in arrays that usernames[0], rooms[0], and buildings[0] go together, as do all the other entries for equal indices.
Does that work 100% of the time? Is it safe? I can think of some ways to make a hard-and-fast association between the groups of inputs, but they involve some mildly irritating javascript and some really obnoxious C#. This seems like it will work out of the box. Eh?
Phil Haack explained very nicely the expected names for your input fields in order to bind them to strongly typed collection in
this blog post. So all you have to do is respect this convention. You might also find thefollowing blog postfrom Steven Sanderson interesting as he explains how this scenario could be implemented in practice. In his example he is using add/remove item buttons but this could very easily be transposed to your scenario in which the number of items to be added is entered in a textbox.