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

时间:2012-06-29 13:43:29

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

我正在使用MVC3的Razor引擎来生成视图,并使用以下代码行生成文本框

 @Html.EditorFor(model => model.AddressLine1)

在相关模型中,我使用数据注释属性将可接受字符数限制为55:

[StringLength(55)]
public string  AddressLine1 { get; set; }

然而,这允许用户输入更长的地址,然后在尝试提交表单时通过验证消息告知。如何将文本框限制为55个字符,以便用户无法输入更多内容?

如果我自己生成文本框,我会使用maxlength属性作为输入类型,但我不确定如何使用Html.EditFor方法获得相同的结果。

3 个答案:

答案 0 :(得分:8)

使用maxlengthTextBoxFor代替EditorFor

EditorFor没有超载允许这样做。

这对你来说可能更有趣: maxlength attribute of a text box from the DataAnnotations StringLength in Asp.Net MVC

答案 1 :(得分:8)

 @Html.TextBoxFor(model => model.AddressLine1, new {maxlength = 55}) 
  

<强>的maxlength
  如果type属性的值是text,email,search,password,tel或url,则此属性指定用户可以输入的最大字符数(以Unicode代码点为单位);对于其他控件类型,它将被忽略。

您也可以在不更改DOM的情况下使用jQuery:

$('#AddressLine1').keypress(function(){
    return this.value.length < 55
})

答案 2 :(得分:0)

$('#AddressLine1').keypress(function(){
    return this.value.length < 55
})

此jQuery函数可在网络浏览器上使用,但在移动设备上不支持,因此在创建每个人都可以访问的网站时,请考虑

相关问题