maxlength attribute of a text box from the DataAnnotations StringLength in MVC2

Posted by Pervez Choudhury on Stack Overflow See other posts from Stack Overflow or by Pervez Choudhury
Published on 2010-03-05T11:36:34Z Indexed on 2010/04/03 6:53 UTC
Read the original article Hit count: 1093

Filed under:
|
|

I am working on an MVC2 application and want to set the maxlength attributes of the text inputs.

I have already defined the stringlength attribute on the Model object using data annotations and it is validating the length of entered strings correctly.

I do not want to repeat the same setting in my views by setting the max length attribute manually when the model already has the information. Is there any way to do this?

Code snippets below:

From the Model:

[Required, StringLength(50)]
public string Address1 { get; set; }

From the View:

<%= Html.LabelFor(model => model.Address1) %>
<%= Html.TextBoxFor(model => model.Address1, new { @class = "text long" })%>
<%= Html.ValidationMessageFor(model => model.Address1) %>

What I want to avoid doing is:

<%= Html.TextBoxFor(model => model.Address1, new { @class = "text long", maxlength="50" })%>

Is there any way to do this?

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about asp.net-mvc-2