Search code examples
c#asp.net-mvchtml-helper

Asp.Net MVC- Html.TextBoxFor - Set Autofocus property to false


I have two input fields on my razor view. One for username and one for password.

If the username has a value passed in through the ViewBag then I don't want to set focus to the username field but rather have focus in the password field. But what happens at the moment is that the first Username input always receives the focus. The "false" value doesn't seem to do anything. I've had a google around and checked some other Stack Overflow posts but i still can't seem to find an answer on this.

I have simple code like so on my view:

@Html.TextBoxFor(m => m.Username, new { @placeholder = "Username", autofocus = (ViewBag.Username == "" ? "autofocus" : "false"), value = ViewBag.Username })

@Html.PasswordFor(m => m.Password, new { @placeholder = "Password", autofocus = (ViewBag.Username == "" ? "false" : "autofocus") })

I know i could just use JQuery to set the focus conditionally but i was hoping there would be a way through the Text Box Html Helper?


Solution

  • Autofocus is a boolean attribute. As per the spec, if it exists, it should be listed as either autofocus="autofocus" or simply autofocus. To "turn it off" it is a case of not adding it as an attribute on the input.

    Following the advice in the excellent answer here, there are a few ways to do what you want. One way is to create an extension method, and you could do it like this:

    Create an extension method like so:

    public static class AttributesExtensions
    {
        public static RouteValueDictionary AutofocusIf(
            this object htmlAttributes, 
            bool autofocus
        )
        {
            var attributes = new RouteValueDictionary(htmlAttributes);
            if (autofocus)
            {
                attributes["autofocus"] = "autofocus";
            }
            return attributes;
        }
    }
    

    Now, when you create your username textbox:

    @Html.TextBoxFor(m => m.Username, new { @placeholder = "Username", value = (string) ViewBag.Username }.AutofocusIf(String.IsNullOrWhiteSpace((string) ViewBag.Username)))