簡體   English   中英

數據注釋MVC

[英]Data Annotation 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"} }
)

謝謝

好吧,您可以始終使用三元運算符?:來代替使用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 { }
)

您可以簡單地使用

if(Model.UserName != null) 
{
    @Html.PasswordFor(model => model.Password, new { required = "This fiels is required"})  
}
else
{
    @Html.PasswordFor(model => model.Password)
}

為什么需要使事情復雜化?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM