Set required attribute on Html.Textbox

2019-02-11 09:47发布

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?

4条回答
淡お忘
2楼-- · 2019-02-11 10:22

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.

查看更多
Juvenile、少年°
3楼-- · 2019-02-11 10:32

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.

查看更多
冷血范
4楼-- · 2019-02-11 10:37

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'.
查看更多
叼着烟拽天下
5楼-- · 2019-02-11 10:45

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.

查看更多
登录 后发表回答