Set required attribute on Html.Textbox
I'm looking to create a Bootstrap styled textbox, specifically, based on the exact example below:
<input class="span3" type="email" required>
Here's what I have so far:
@Html.TextBox("CustomerEmail", null, new { @class = "input-xlarge", type = "email", required = "required" })
However, required = "required"
clearly doesn't return just required
.
So, my question is, is there any way I can force it to return required like in the first example above when using Html.Textbox?
Solution 1:
i think you should use like this
@Html.TextBoxFor(model => model.Name, new { @class = "text", type = "email", required = "required" })
i think this will help you.
Solution 2:
Try
new { required = string.Empty}
As an aside, according to the W3C docs, required
is a Boolean attribute, and I quote:
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.
Therefore
required
required="required"
required=""
all mean the same thing.
Solution 3:
You seem to have applied a different class to the textbox: input-xlarge
, whereas in your desired markup it's called span3
.
So:
@Html.TextBox(
"CustomerEmail",
null,
new {
@class = "span3",
type = "email",
required = "required"
}
)
As far as the required part is concerned, the correct syntax here is required="required"
, otherwise you simply get broken HTML.
Solution 4:
I noticed that you can also use.
required="true"
The interesting thing is that you get a warning message in Visual Studio 2015 regardless. I wonder if this is a problem with a need for updating.
Warning Message:
Severity Code Description Project File Line Suppression State
Message Validation (ASP.Net): Attribute 'required' is not a valid attribute of element 'TextBox'.