数据注释MVC

时间:2014-06-11 09:39:39

标签: c# jquery html asp.net-mvc

如果我的用户名模型中有值,我该如何添加必填字段。

我有:

@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"} }
)

谢谢

2 个答案:

答案 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)
}

为什么你需要复杂化?