【问题标题】:How to make a boolean HTML5 attribute 'conditional' in ASP.Net MVC?如何在 ASP.Net MVC 中使布尔 HTML5 属性“有条件”?
【发布时间】:2016-04-30 18:26:14
【问题描述】:

我正在使用 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 : ""`

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

【问题讨论】:

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


【解决方案1】:

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

@{
    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);

【讨论】:

  • 这行得通。但是if条件需要在{ }之间,否则编译失败。
【解决方案2】:

在控制器中检查您的情况,如果为真,则设置ViewBag.Tag = autofocus,然后在您的视图中

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

【讨论】:

  • 我不明白这个解决方案。你能详细说明一下吗?
  • 在您的控制器中 if ( !String.IsNullOrEmpty(Model.UserName)){ViewBag.Tag="autofocus"} 如果条件不成立,那么您的视图中有 ViewBag.tag什么都不做,如果是真的,它只是打印添加自动对焦作为属性。
  • ViewBag 是 C# 中的动态类型,因此您可以像我们在上面的示例中那样在运行时为其添加属性。
  • 但我有一个包含多个字段的表单。遇到这种情况我该怎么办?
  • 对不起,我不清楚您的评论,您只能对一个表单字段使用自动对焦。
猜你喜欢
  • 2011-02-06
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
相关资源
最近更新 更多