mvc3 maxLength input
Asked Answered
I

3

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.

Icelander answered 28/5, 2012 at 12:16 Comment(0)
C
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.

C answered 29/5, 2012 at 6:44 Comment(2)
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?Antinucleon
You have to write your own metadata provider (possibly) and a custom helper that adds to HtmlOptions before rendering (a simple wrapper basically).C
G
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" } })
Gildus answered 21/10, 2015 at 15:52 Comment(1)
Upvoting because this worked for me: @Html.EditorFor(model => model.CourseNumber, new { htmlAttributes = new { maxlength=10 } })Pretext
A
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://mcmap.net/q/236749/-maxlength-attribute-not-generating-client-side-validation-attributes

Annular answered 3/1, 2015 at 5:51 Comment(2)
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.Bindery
StringLength and MaxLength (DataAnnotation) are for jquery validate and needs javascript.Relevant

© 2022 - 2024 — McMap. All rights reserved.