Search code examples
validationasp.net-coreasp.net-core-mvcunobtrusive-validationtag-helpers

Mvc Core: Validation attributes are generated once for dublicated names


This is a question just like an old one but in the old one, the reason for that is marked as the answer.

My page, there is a form that contains several items. Each item contains a few elements so their name is duplicated.

<form ...>
    .....
    <table class="details">
        <thead>
            <tr>
                <th>Prop1</th>
                <th>Prop2</th>
            </tr>
        </thead>
        <tbody>
            @foreach(var item in Model.Items)
            {
               @await Html.PartialAsync("partial-view-name", detail)
            }
        </tbody>
    </table>
    ...
</form>

The partial

....
<tr>
   <td><input asp-for="Prop1" /></td>
   <td><input asp-for="Prop2" /></td>
</tr>

As mentioned here this is the designed behavior, but I wondered if there is any way to override it.


Solution

  • I found a solution to add a prefix to the HTML fields so the name would be different in the iterations.

    @{ ViewData.TemplateInfo.HtmlFieldPrefix = Model.ID; }
    <tr>
       <td><input asp-for="Prop1"/></td>
       <td><input asp-for="Prop2"/></td>
    </tr>