Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a boolean HTML5 attribute 'conditional' in ASP.Net MVC?

I'm using ASP.Net MVC (5.2.3.0) to create a form field:

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

So far so good, but now I like to make the autofocus attribute conditional. How would I go about?

The autofocus attribute is a boolean attribute and W3C states:

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

The following doesn't work in MVC, because it still renders the autofocus attribute causing the browser to do the auto focus:

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

Does anybody know how to solve this problem?

like image 408
Kees C. Bakker Avatar asked Jan 24 '16 12:01

Kees C. Bakker


1 Answers

You could create an attribute dictionary somewhere before in the view:

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

and use it in the TextBoxFor()

@Html.TextBoxFor(x => x.UserName, usernameAttrs);
like image 177
Linus Caldwell Avatar answered Sep 28 '22 10:09

Linus Caldwell