MVC 2 EditorFor MaxLength and Size

How to set the maximum length and size of a text field in MVC 2? This question has been asked a few questions. As a newbie to MVC, I found that none of the solutions work - perhaps because I am not doing it right.

In any case, I wonder if there are any better solutions, as the previous questions are asked when MVC 2 was in beta.

+7
asp.net-mvc
source share
2 answers

It's easy, you just get extra htmlAtttributes

<%= Html.TextBoxFor(model => model.Member, new { maxlength = "20", width = "15" }) %> <%= Html.TextBoxFor(model => model.Member, new { maxlength = "20", style = "width:200px;" }) %> 
+9
source share

The above solution works, but if you have multiple instances of this field, it would be easier to set it in a model or view model. Be careful with changing the actual model, because they may be unstable when upgrading.

Example: In a model or view model.

 [DisplayName("Notes")] [MaxLength(500, ErrorMessage="Maximum length of notes field is 500 characters...")] [DataType(DataType.MultilineText)] public string Notes { get; set; } 

To test it on sending, you will need the following in your web.config.

 <add key="ClientValidationEnabled" value="true" /> <add key="UnobtrusiveJavaScriptEnabled" value="true" /> 

Make sure you link somewhere to validation JA files, preferably in Shared / _Layout or on the page itself ...

 <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 

Finally, make sure you include the validation message in cshtml.

 @Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control", rows = "5", @placeholder = "Notes", title = "Enter any notes..." } }) @Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" }) 

Build a solution and test. Hope this helps someone else find a solution.

0
source share

All Articles