在循环中使用时 asp 验证存在问题



我在下面代码中的 span 元素上使用 asp-validation-for 时遇到了问题。

<div class="form-group">
@if (Model.Property.Options.ElementAt(i).OptionTypeId == PropertyOptionType.CheckBox)
{
var ItemChecked = (Model.Property.Options.ElementAt(i).OptionValue == "on") ? " checked" : "";
<text><input type="checkbox" class="form-check-input" name="Options[@i].Code" id="Options[@i].Code" @ItemChecked data-val="false" />
<label class="form-check-label" for="Options[@i].Value">&nbsp;@(Model.Property.Options.ElementAt(i).OptionValue)</label></text>
}
else if (Model.Property.Options.ElementAt(i).OptionTypeId == PropertyOptionType.List)
{
<label class="control-label">
@Model.Property.Options.ElementAt(i).OptionValue
</label>
<select class="form-control" name="Options[@i].Code"></select>
}
<span class="text-danger field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Options.@(i).Code"></span>

当它以 HTML 呈现时,它显示为

<span class="text-danger field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Options.[3].Code"></span>

但是没有验证错误消息进入跨度。当设置为"全部"时,它们将在页面级别验证摘要中选取,因此不显眼的代码都正常工作,但跨度的 ID 被方括号破坏。

有什么想法吗? 谢谢 马克

若要显示验证摘要,需要包括:

@Html.ValidationSummary(false/*excludePropertyErrors?*/, "", new { @class = "text-danger" })

要显示特定于字段的错误消息,您需要使用ValidationMessageFor

@Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.StudentName, "", new { @class = "text-danger" }) 

请参阅本教程

不要手动生成验证范围,html 助手会为您完成...您将需要这样的东西:

@for (int i = 0; i < Model.Property.Options.Count(); i++)
{
/* this one generates the input */
@Html.EditorFor(m => m.Property.Options[i], new { htmlAttributes = new { @class = "form-control" } })
/* this one generates the validation message */
@Html.ValidationMessageFor(m => m.Property.Options[i], "", new { @class = "text-danger" })
}

最新更新