2

In below link there is add button which allows you to ADD multiple textbox which i am using on my application.

http://jsfiddle.net/cN5SR/200/

Now I want to know how can I bind that array of string value with my ViewModel.

let's say if my property in ViewModel is as below:

Public class MyViewmodel
{
   Public string[] players { get; set; }
}
updev
  • 623
  • 5
  • 14
  • 32
  • 1
    If all of the textboxes are named "players" the ModelBinder will add each text box value to the array. The other option is to name each text box with an index: players[0], players[1], etc but then you need to manage the indexes and NOT skip one – Nick Bork Apr 06 '12 at 01:01
  • DO you mean it will by default make the array string? – updev Apr 06 '12 at 01:07
  • if each text box is the same name, you're basically posing "player=player1&player=player2&player=player3" and that will result in the array being auto-constructed by the ModelBinder – Nick Bork Apr 06 '12 at 01:13

2 Answers2

1

If I did it statically, I would have done it as follows using Razor syntax.

@for(int i = 0; i < Model.players.Length; i++)
{
   @Html.EditorFor(m => m.players[i]);
}

This results in the following markup:

<input class="text-box single-line" id="players_0_" name="players[0]" type="text" value="Bob" />
<input class="text-box single-line" id="players_1_" name="players[1]" type="text" value="Sam" />

So if you add two inputs using javascript that looks as follows and post it to your controller, the default binder will create an players array with 4 items. I hope you see the patter.

<input class="text-box single-line" id="players_2_" name="players[2]" type="text" value="Pete" />
<input class="text-box single-line" id="players_3_" name="players[3]" type="text" value="Dirk" />

There are some challenges. I have done this before and had a couple issues around deletions. I can't remember the exact issues and what I did to fix it at this point.

bloudraak
  • 5,902
  • 5
  • 37
  • 52
0

Steven Sanderson wrote a very nice blog post on exactly this subject.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • While this answer is over a year old and the link is helpful it would be better if you post the essential parts of the answer here, on this site, or your post risks being deleted [See the FAQ where it mentions answers that are 'barely more than a link'.](http://stackoverflow.com/faq#deletion) You may still include the link if you wish, but only as a 'reference'. The answer should stand on its own without needing the link. – Taryn Nov 04 '14 at 10:46