我正在使用 MVC3 的 Razor 引擎生成 View ,并使用以下代码生成文本框
@Html.EditorFor(model => model.AddressLine1)
在相关模型中,我使用数据注释属性将可接受的字符数限制为 55:
[StringLength(55)]
public string AddressLine1 { get; set; }
然而,这允许用户输入更长的地址,然后在他们尝试提交表单时通过验证消息告知。如何将文本框限制为 55 个字符,以便用户无法输入超过 55 个字符的字符?
如果我自己生成文本框,我会为输入类型使用 maxlength 属性,但我不确定如何使用 Html.EditFor 方法获得相同的结果。
最佳答案
@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.
您还可以在不更改 DOM 的情况下使用 jQuery:
$('#AddressLine1').keypress(function(){
return this.value.length < 55
})
关于asp.net - 使用 Razor Html.EditorFor 时限制文本框中字符的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11262923/