如果我的用户名模型中有值,我该如何添加必填字段。
我有:
@Html.PasswordFor(
model => model.Password,
new { required = "This field is required" }
)
我想:
@Html.PasswordFor(
model => model.Password,
new { if (Model.UserName != null) {required = "This field is required"} }
)
谢谢
答案 0 :(得分:1)
您可以使用三元运算符if
?:
语句
@Html.PasswordFor(
model => model.Password,
new { required = Model.UserName != null ? "This field is required" : null }
)
或者(如果将required
设置为null不起作用)那么你可以使用它一级:
@Html.PasswordFor(
model => model.Password,
Model.UserName != null
? new { required = "This field is required" }
: new { }
)
答案 1 :(得分:1)
您只需使用
即可if(Model.UserName != null)
{
@Html.PasswordFor(model => model.Password, new { required = "This fiels is required"})
}
else
{
@Html.PasswordFor(model => model.Password)
}
为什么你需要复杂化?