0

I have a view that allows the user to inset multiple elements of the same type.

 @foreach (var gm in Model)
    {
        <tr><td>
                @Html.TextBoxFor(model => gm.name)
        </tr></td>
    }

But, when I saw the generated HTML it is duplicating the id and the name

<tr><td>
        <input id="gm_name" name="gm.name" type="text" value="" />
</td></tr>
<tr><td>
        <input id="gm_name" name="gm.name" type="text" value="" />
</td></tr>

Is there a way to automatically add an 1,2,3,etc and the end of id, example:

<tr><td>
            <input id="gm_name1" name="gm.name1" type="text" value="" />
    </td></tr>
    <tr><td>
            <input id="gm_name2" name="gm.name2" type="text" value="" />
    </td></tr>

I can do that if I generate all the html, but, is there an automatically way to achieve that?

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
roncansan
  • 2,310
  • 6
  • 27
  • 34

2 Answers2

1

For what it's worth you probably want.

<tr><td>
        <input id="gm_0__name" name="gm[0].name" type="text" value="" />
</td></tr>
<tr><td>
        <input id="gm_0__name" name="gm[1].name" type="text" value="" />
</td></tr>

It appears from the source code that the ExpressionHelper method used to translate the name from the model expression understands about array indexing expressions. You might try something like:

@for (int i = 0; i < Model.Count; ++i )
{
   <tr><td>
            @Html.TextBoxFor(m => m[i].name)
    </tr></td>
}

I'll confess that I haven't tried this in MVC3 so I'm not sure whether it will work or not. In earlier versions I built this sort of thing by hand.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
1

Rather than using TextBoxFor, just use the TextBox method, and you can specify the name you want it to use. Something like this should work, I think:

 @foreach (int i = 0; i < Model.Count; i++)
    {
        var gm = Model[i];
        <tr><td>
                @Html.TextBox("gm.name" + i, gm.name, new {id = "gm_name" + i})
        </tr></td>
    }
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315