如何制作布尔HTML5属性'条件'在ASP.Net MVC?

时间:2016-01-24 12:25:26

标签: c# asp.net asp.net-mvc html5 razor

我使用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表示状态:

  

注意:值" true"和"假"布尔值不允许   属性。要表示false值,必须使用该属性   完全省略。

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

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

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

2 个答案:

答案 0 :(得分:3)

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

res1 <- input2_tbl[, tstrsplit(unlist(strsplit(gsub('[{}"]', '', 
   b),',', fixed=TRUE)), ":(?=[^:]+$)", perl=TRUE) ,
         by = .(a, c)][V2 < 3]
setnames(res1, 3:4, c("b", "s"))
res1
#     a c                 b s
# 1: AA 1 99:1d:3u:7y:89:67 1
# 2: AA 1 99:1D:34:YY:T6:Y6 2

并在@{ 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()

答案 1 :(得分:0)

检查控制器中的状况,如果设置为ViewBag.Tag = autofocus,则在视图中

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