Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 数据注释MVC_C#_Jquery_Html_Asp.net Mvc - Fatal编程技术网

C# 数据注释MVC

C# 数据注释MVC,c#,jquery,html,asp.net-mvc,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

只有在用户名模型中有值时,我才能添加必填字段

我有:

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

谢谢

好的,您可以使用三元运算符
?:

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

你为什么要把事情复杂化?

谢谢你的回答@zakzak酷毙了,第一个版本最终成功了吗?@Html.PasswordFor(model=>model.Password,model.UserName!=null?new{required=”“}:null))是的,对于null它工作得很好,再次感谢:)