如何使用razor引擎在View中为TextAreaFor添加maxlength

Kam*_*mil 13 html asp.net-mvc razor asp.net-mvc-3

我在使用Razor Engine实现的View中有一个TextArea()控件.

@Html.TextArea("EventNature",new { style = "width: 200px; height: 100px;" })
Run Code Online (Sandbox Code Playgroud)

如何为此控件设置Maxlength属性?
是否在RazorEngine中有内置的属性,还是我必须使用脚本?

gdo*_*ica 34

你可以这样做:

@Html.TextArea("EventNature",new { maxlength=50, // or other value
                                  style = "width: 200px; height: 100px;" })
Run Code Online (Sandbox Code Playgroud)

请注意,这是一个HTML5属性

maxlength HTML5
用户可以输入的最大字符数(Unicode代码点).如果未指定,则用户可以输入无限数量的字符.

MDN


对HTML <5的Javascript(使用jQuery)验证:

$('#EventNature').keypress(function(){
    if (this.value.length >= 10) // allowing you to enter only 10 chars.
    return false;        
});?
Run Code Online (Sandbox Code Playgroud)

DEMO


Tom*_*kel 5

这也适用于TextAreaFor助手,该助手具有多个匿名类型new

确认可以在带有MVC 5的Visual Studio 2015中正常工作

@Html.TextAreaFor(model => model.Comments, 5, 500, new {maxlength=4000,  @class = "form-control" })
Run Code Online (Sandbox Code Playgroud)