asp.net - 使用 Razor Html.EditorFor 时限制文本框中字符的长度

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

我正在使用 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/

相关文章:

html - 双列,其中第二列自动调整其宽度

asp.net-mvc-3 - 复杂的验证场景

c# - .NET Core 2.0 中的 HttpWebRequest 抛出 302 发现异常

c# - 遍历 gridview 并不总是有效

c# - 动态添加的 ASP.Net 按钮无法调用 Click 或 CommandArgument 事件

html - 尝试将文本和图像的链接垂直居中

html - 用于连续元素的 CSS 或 XPath 选择器

第二次执行 onclick 模式对话框后,Jquery 不清空部分 View

jquery - 如何在 Jquery-UI 自动完成中显示图像

c# - 如何检测我的 .NET 程序集是从网站运行还是从桌面计算机运行?