Limiting the length of characters in a text field when using Razor Html.EditFor

I use the MVC3 Razor engine to generate views and has the following line of code generating a text field

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

In the corresponding model, I use the data annotation attribute to limit the number of valid characters to 55:

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

However, this allows the user to enter a longer address, which must then be transmitted via a validation message when trying to submit the form. How can I limit the text box to 55 characters so that the user cannot enter it anymore?

If I generated the text field myself, I would use the maxlength attribute for the input type, but I'm not sure how to achieve the same results using the Html.EditFor method.

+7
source share
2 answers

Use maxlength and TextBoxFor instead of EditorFor

EditorFor does not have an overload that allows you to do this.

This might be even more interesting for you: the maxlength attribute of a text field from DataAnnotations StringLength in Asp.Net MVC

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

MaxLength
If the value of the type attribute is text, email address, search, password, tel or url, this attribute defines the maximum number of characters (in Unicode code points) that the user can enter; for other types of control it is ignored.

You can also use jQuery without changing the DOM:

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

All Articles