在Html.Textbox上设置必需属性

时间:2013-01-11 11:05:17

标签: html asp.net-mvc-3 razor

我希望创建一个Bootstrap样式的文本框,具体来说,基于下面的确切示例:

<input class="span3" type="email" required>

这是我到目前为止所拥有的:

@Html.TextBox("CustomerEmail", null, new { @class = "input-xlarge", type = "email", required = "required" })

但是,required = "required"显然不会仅返回required

所以,我的问题是,在使用Html.Textbox时,有什么方法可以像上面第一个例子中那样强制它返回?

4 个答案:

答案 0 :(得分:64)

我认为你应该像这样使用

 @Html.TextBoxFor(model => model.Name, new { @class = "text", type = "email", required = "required" })

我认为这会对你有帮助。

答案 1 :(得分:17)

尝试

new { required = string.Empty}

顺便说一句,根据W3C文档,requiredBoolean attribute,我引用:

  

元素上存在布尔属性表示真值,缺少属性表示false值。   如果该属性存在,则其值必须是空字符串,或者是属性规范名称的ASCII不区分大小写匹配的值,没有前导或尾随空格。

因此

required
required="required"
required=""

都意味着同样的事情。

答案 2 :(得分:2)

您似乎在文本框中应用了不同的类:input-xlarge,而在您想要的标记中,它被称为span3

所以:

@Html.TextBox(
    "CustomerEmail", 
    null, 
    new { 
        @class = "span3", 
        type = "email", 
        required = "required" 
    }
)

就所需部分而言,此处的正确语法为required="required",否则您只会破坏HTML。

答案 3 :(得分:1)

我注意到你也可以使用。

required="true"

有趣的是,无论如何,您都会在Visual Studio 2015中收到警告消息。我想知道这是否是需要更新的问题。

警告讯息:

Severity    Code    Description Project File    Line    Suppression State
Message     Validation (ASP.Net): Attribute 'required' is not a valid attribute of element 'TextBox'.
相关问题