使用 Razor 的 Html.EditFor 时限制文本框中字符的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11262923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limiting the length of characters in a textbox while using Razor's Html.EditFor
提问by Sperick
I'm using MVC3's Razor engine to generate views and have the following line of code generating a textbox
我正在使用 MVC3 的 Razor 引擎生成视图,并使用以下代码行生成文本框
@Html.EditorFor(model => model.AddressLine1)
In the relevant model I'm using a data annotation attribute to limit the number of acceptable characters to 55:
在相关模型中,我使用数据注释属性将可接受的字符数限制为 55:
[StringLength(55)]
public string AddressLine1 { get; set; }
However this allows the user to type in a longer address only to be then told via a validation message when they try and submit the form. How can I limit the textbox to 55 characters so that the user is unable to type any more than that in?
然而,这允许用户输入更长的地址,然后在他们尝试提交表单时通过验证消息被告知。如何将文本框限制为 55 个字符,以便用户无法输入更多字符?
If I was generating the text box myself I would use the maxlength attribute for an input type but I'm not sure how to achieve the same results using the Html.EditFor method.
如果我自己生成文本框,我会使用 maxlength 属性作为输入类型,但我不确定如何使用 Html.EditFor 方法获得相同的结果。
回答by gdoron is supporting Monica
@Html.TextBoxFor(model => model.AddressLine1, new {maxlength = 55})
maxlength
If the value of the type attribute is text, email, search, password, tel, or url, this attribute specifies the maximum number of characters (in Unicode code points) that the user can enter; for other control types, it is ignored.
maxlength
如果 type 属性的值为 text、email、search、password、tel 或 url,则该属性指定用户可以输入的最大字符数(以 Unicode 代码点为单位);对于其他控件类型,它被忽略。
You can also use jQuery without changing the DOM:
您还可以在不更改 DOM 的情况下使用 jQuery:
$('#AddressLine1').keypress(function(){
return this.value.length < 55
})
回答by Rapha?l Althaus
Use maxlength
and a TextBoxFor
instead of EditorFor
使用maxlength
和TextBoxFor
代替EditorFor
EditorFor
has no overload that permit to do that.
EditorFor
没有允许这样做的过载。
This could be even more interesting for you : maxlength attribute of a text box from the DataAnnotations StringLength in Asp.Net MVC
这对您来说可能更有趣: Asp.Net MVC 中 DataAnnotations StringLength 文本框的 maxlength 属性
回答by befree2j
$('#AddressLine1').keypress(function(){
return this.value.length < 55
})
This jQuery function works on web browsers but on mobile this is not supported, so when creating a site being accessed by everyone consider that
这个 jQuery 函数适用于 Web 浏览器,但在移动设备上不受支持,因此在创建每个人都访问的站点时,请考虑