CodeGo.net>如何在ASP.Net MVC中使布尔HTML5属性“有条件”?

我正在使用ASP.Net MVC(5.2.3.0)创建一个表单字段:

@Html.TextBoxFor(
    x => x.UserName, 
    new { 
        @class = "form-control", 
        placeholder = "Enter your username", 
        required = true, 
        autofocus = true 
});

到目前为止,一切都很好,但是现在我希望将autofocus属性设置为条件.我该怎么办?

autofocus属性是一个布尔属性,状态为W3C

Note: The values “true” and “false” are not allowed on boolean
attributes. To represent a false value, the attribute has to be
omitted altogether.

以下内容在MVC中不起作用,因为它仍然呈现autofocus属性,导致浏览器进行自动聚焦:

autofocus = String.IsNullOrEmpty(this.Model.UserName)
autofocus = String.IsNullOrEmpty(this.Model.UserName) ? null : ""`

有人知道如何解决这个问题吗?

解决方法:

您可以在视图之前的某个位置创建属性字典:

@{
    var usernameAttrs = new Dictionary<string, object>
    {
        {"class ", "form-control"},
        {"placeholder  ", "Enter your username"},
        {"required", true},
    };

    if (String.IsNullOrEmpty(this.Model.UserName))
    {
        usernameAttrs.Add("autofocus", true);
    }
}

并在TextBoxFor()中使用它

@Html.TextBoxFor(x => x.UserName, usernameAttrs);
上一篇:$.ajax 调用 Asp.Net Core Razor Page 后台代码


下一篇:.net5 core Razor项目实战系列之十一:操作日志查询功能的实现