Set required attribute on Html.Textbox

Htmlasp.net Mvc-3Razor

Html Problem Overview


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?

Html Solutions


Solution 1 - Html

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 - Html

Try

new { required = string.Empty}

As an aside, according to the W3C docs, required is a [Boolean attribute][1], 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. [1]: http://www.w3.org/TR/html5/infrastructure.html#boolean-attribute

Solution 3 - Html

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 - Html

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'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLiamGuView Question on Stackoverflow
Solution 1 - HtmlRajpurohitView Answer on Stackoverflow
Solution 2 - HtmlPaulineView Answer on Stackoverflow
Solution 3 - HtmlDarin DimitrovView Answer on Stackoverflow
Solution 4 - HtmlNetsurfer2View Answer on Stackoverflow