20

this may be kind of general but i want to limit the number of character inpit in an editorfor field.

@html.EditorFor(m=>m.id,new {@maxlength="10"})

This does not seem to work.

tereško
  • 58,060
  • 25
  • 98
  • 150
CodeNoob
  • 411
  • 1
  • 7
  • 24

3 Answers3

30

Try changing it to

@Html.TextBoxFor(m=> m.id,  new { maxlength="10" });

EditorFor uses the templates, which you can override yourself. I don't think they take into account the attributes you pass in like this. The TextBoxFox<> generates it in code, and should work fine.

Andrew
  • 8,322
  • 2
  • 47
  • 70
  • And what if we need to combine. I must use editor for watermarks, and still need maxlength. here is my editor code `@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { placeholder = ViewData.ModelMetadata.Watermark })` how can I get "max" from metadata? – Pawel Cioch Jul 25 '14 at 21:54
  • You have to write your own metadata provider (possibly) and a custom helper that adds to HtmlOptions before rendering (a simple wrapper basically). – Andrew Jul 28 '14 at 01:44
13

I was able to get it working in IE11 using the EditorFor and using multiple attributes.

@Html.EditorFor(model => model.CourseNumber, new { htmlAttributes = new { @style = "width:100px", @maxlength="10" } })
Skatox
  • 4,237
  • 12
  • 42
  • 47
tnt
  • 139
  • 1
  • 2
  • 1
    Upvoting because this worked for me: `@Html.EditorFor(model => model.CourseNumber, new { htmlAttributes = new { maxlength=10 } })` – Reyhn Mar 22 '16 at 10:01
4

In MVC3, this is better:

[StringLength(10, ErrorMessage = "Name cannot be longer than 10 characters.")]
public string Name { get; set; }

Specifies the minimum and maximum length of characters that are allowed in a data field. as in this https://stackoverflow.com/a/6802739/2127493

Community
  • 1
  • 1
Azarsa
  • 1,278
  • 3
  • 27
  • 37
  • 1
    That did not work for me, neither `MaxLength` nor `StringLength` added the attribute `maxlength`, instead I only got `data-val-length-max` and `data-val-maxlength-max`. – MushyPeas Dec 20 '16 at 14:12
  • StringLength and MaxLength (DataAnnotation) are for jquery validate and needs javascript. – bang Mar 17 '20 at 12:52