问题
I am trying to use TagHelpers when editing a list of items.
This is the code inside the view where helpers are employed:
@for (var i = 0; i < Model.Items.Count; i++)
{
<tr>
<td>
<input asp-for="Items[i].Name" />
<span asp-validation-for="Items[i].Name" class="text-danger" />
</td>
</tr>
}
Input helpers are working as expected, ModelState is properly filled with validation errors but validation errors are not shown to the user.
I'm guessing there's a problem with rendering validation tags.
<td>
<input class="input-validation-error" data-val="true" data-val-required="The Name field is required." id="Items_0__Name" name="Items[0].Name" value="" type="text">
<span class="text-danger field-validation-error" data-valmsg-for="Items[0].Name" data-valmsg-replace="true"></span>
</td>
It could be that input Id is Items_0__Name
(with underscores) but validation tag looks for Items[0].Name
.
Is there a workaround to make the validation work with this?
回答1:
I have never seen any problems using a foreach
@foreach (var item in Model.Items)
{
<tr>
<td>
<input asp-for="item.Name" />
<span asp-validation-for="item.Name" class="text-danger" />
</td>
</tr>
}
来源:https://stackoverflow.com/questions/34732092/taghelper-validation-when-editing-a-list