how to prevent html input id duplication on asp.net mvc 3 when a model contains multiple elements

后端 未结 2 546
生来不讨喜
生来不讨喜 2021-01-27 11:03

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

 @foreach (var gm in Model)
    {
        
                         


        
相关标签:
2条回答
  • 2021-01-27 11:31

    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>
        }
    
    0 讨论(0)
  • 2021-01-27 11:49

    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.

    0 讨论(0)
提交回复
热议问题