这似乎应该很容易实现,但我发现它具有挑战性。 我的视图模型中有一个对象列表,需要进行验证,不引人注意。
我已经查看了FluentValidation,但似乎be a bug in the collections validation的实现似乎没有触发不显眼的验证器。不确定是否有使用数据注释的方法 对于一个对象列表,其中验证将不引人注意地(和服务器端)
我正在寻找有关如何执行此操作的建议。感谢
对象
public class NewClubSponsor
{
public string SponsorContactName { get; set; }
public string SponsorContactEmail { get; set; }
public string SponsorContactPhone { get; set; }
}
我在View模型中声明了NewClubSponsor对象列表
public List<NewClubSponsor> Sponsors { get; set; }
视图
<div id="addCosponsorSection">
<!-- We have at least 1 existing sponsor -->
@if (Model.Sponsors != null)
{
for (var i = 0; i < Model.Sponsors.Count; i++)
{
string sponsorDivId = "sponsorclubname" + i.ToString();
string deleteLink = "<a class=\"icon delete cosponsor\" data-attr-divid=\""+@sponsorDivId+"\" data-attr-id=" + @Model.Sponsors[i].Id + "></a>";
<div id="@sponsorDivId">
<div class="formColumn1"><label for="sponsorclubname1">Sponsor club name</label></div>
<div class="formColumn2">@Html.EditorFor(x => x.Sponsors[i].SponsorContactName)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactName)
</div>
</div>
<div class="formColumn3">@Html.EditorFor(x => x.Sponsors[i].SponsorContactEmail)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactEmail)
</div>
</div>
<div class="formColumn4">@Html.EditorFor(x => x.Sponsors[i].SponsorContactPhone)@(i > 0 ? Html.Raw(deleteLink) : Html.Raw(""))
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[i].SponsorContactPhone)
</div>
</div>
</div>
<div class="clear"></div>
}
}
else
{
<!-- No sponsors added yet. We need at least 1 sponsor -->
<div id="sponsorclubname1">
<div class="formColumn1"><label for="sponsorclubname1">Sponsor club name</label></div>
<div class="formColumn2">@Html.EditorFor(model => model.Sponsors[0].SponsorContactName)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[0].SponsorContactName)
</div>
</div>
<div class="formColumn3">@Html.EditorFor(model => model.Sponsors[0].SponsorContactEmail)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[0].SponsorContactEmail)
</div>
</div>
<div class="formColumn4">@Html.EditorFor(model => model.Sponsors[0].SponsorContactPhone)
<div class="messageBottom">
@Html.ValidationMessageFor(model => model.Sponsors[0].SponsorContactPhone)
</div>
</div>
</div>
<div class="clear"></div>
<!-- END Static HTML -->
}
</div>
答案 0 :(得分:1)
您可以在组成列表的对象中添加数据注释。 这将添加数据有效和requerire属性...
但是,如果列表是动态创建的,则需要在表单中添加新项目时绑定验证逻辑(如果您通过JS添加它)。