Asp.net-mvc – maxlength attribute of a text box from the DataAnnotations StringLength in Asp.Net MVC

asp.net-mvcvalidation

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" })%>

I want to get this output:

<input type="text" name="Address1" maxlength="50" class="text long"/>

Is there any way to do this?

Best Answer

If you're using unobtrusive validation, you can handle this client side as well:

$(document).ready(function ()
{
    $("input[data-val-length-max]").each(function ()
    {
        var $this = $(this);
        var data = $this.data();
        $this.attr("maxlength", data.valLengthMax);
    });
});