我有一个表单,在某些情况下需要描述字段,而在其他情况下则不需要。最初,它始终是必需的,我在模型中具有必需的属性,如下所示:
[DisplayName("Description")]
[Required(ErrorMessage = "Please enter a description.", AllowEmptyStrings = false)]
public string PaymentDescription { get; set; }
现在我们只希望在某些情况下才需要这个。所以我从模型中删除了所需的数据注释。我尝试了一些方法,包括:
@if (isDescriptionRequired)
{
@Html.TextBoxFor(m => m.PaymentDescription, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
@Html.ValidationMessageFor(m => m.PaymentDescription, "Please enter a description.")
}
else
{
@Html.TextBoxFor(m => m.PaymentDescription, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
}
但那不起作用。根据某些数据条件动态设置模型属性的必需属性的最合适方法是什么?我对在视图中坚持逻辑之外的其他方法持开放态度。最重要的是我需要有时需要该字段,而其他时间则不需要。谢谢你的帮助。
===编辑2015年8月21日上午8:00 CST ===
在调查MVC Foolproof Validation和其他一些[RequiredIf]扩展后,我选择了更简单的东西。我不清楚如果万无一失地使用MVC 4,其他解决方案似乎不必要的复杂,缺乏客户端验证,或缺乏足够的跨浏览器测试客户端验证脚本。
在模型中粘贴2个属性以表示单个属性:
// Property 1 of 2 to represent Description. Work around for requiring Description in special cases.
[DisplayName("Description")]
public string PaymentDescription { get; set; }
// Property 2 of 2 to represent Description. Work around for requiring Description in special cases.
[DisplayName("Description")]
[Required(ErrorMessage = "Payment description is required.", AllowEmptyStrings = false)]
public string PaymentDescriptionRequired { get; set; }
在视图中有条件地显示相关属性的控件。
if (Model.RequirePaymentApproval)
{
@Html.LabelFor(m => m.PaymentDescriptionRequired, new { @class = "control-label" })
@Html.TextBoxFor(m => m.PaymentDescriptionRequired, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
@Html.ValidationMessageFor(m => m.PaymentDescriptionRequired)
}
else
{
@Html.LabelFor(m => m.PaymentDescription, new { @class = "control-label" })
@Html.TextBoxFor(m => m.PaymentDescription, new { @class = "form-control", @placeholder = "Description", @maxlength = "200" })
@Html.ValidationMessageFor(m => m.PaymentDescription)
}
然后在控制器帖子中评估条件属性bool(RequirePaymentApproval),并将所需值分配给非必需属性,或从ModelState中删除所需属性。
if (model.RequirePaymentApproval)
{
model.PaymentDescription = model.PaymentDescriptionRequired;
}
else
{
ModelState.Remove("PaymentDescriptionRequired");
}
if (ModelState.IsValid) {
// Save changes
}
这种方法的好处是能够使用内置的Microsoft数据注释验证代码,该代码具有跨浏览器兼容性的可靠记录。而且相对容易理解。我不喜欢的是它似乎很冗长,我不喜欢在视图和控制器中都坚持使用条件验证逻辑。
也许微软将来会扩展数据注释库,以处理更多这样的现实场景。
我现在暂时不开放,因为比我更好的开发人员可能会有更优雅的建议。感谢。
相关研究: