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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With