Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 - Data Annoation and Max Length/Size for Textbox Rendering

I know on the Razor View file, we can do something like this @Html.TextBox("username", null, new { maxlength = 20, autocomplete = "off" })

However, I am hoping to create a model for the MVC that can be used to create a form with explicitly defined the size and max length of the textboxes. I try [StringLength(n)] on top of the properties of the model, but that seems to only do the validation ratherh set the size of the textbox.

Is there anyway that we can define the length of the text field as a data annotation on top of a property of a model?

So ultimately, we could just create the whole form by using razor to map to a model rather than explicitly pick up the model properties one by one in order to set the textbox size.

like image 697
frostshoxx Avatar asked Aug 29 '11 14:08

frostshoxx


2 Answers

Here is a outline of a custom helper that uses StringLengthAttribute.

public class MyModel
{
    [StringLength(50)]
    public string Name{get; set;}
}

public MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, 
      Expression<Func<TModel, TProperty>> expression)
{

    var attributes = new Dictionary<string, Object>();
    var memberAccessExpression = (MemberExpression)expression.Body;
    var stringLengthAttribs = memberAccessExpression.Member.GetCustomAttributes(
        typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true);

    if (stringLengthAttribs.Length > 0)
    {
        var length = ((StringLengthAttribute)stringLengthAttribs[0]).MaximumLength;

        if (length > 0) 
        {
             attributes.Add("size", length);
             attributes.Add("maxlength", length);
        }
    }

    return helper.TextBoxFor(expression, attributes);
}
like image 74
Eranga Avatar answered Sep 27 '22 16:09

Eranga


Does this not work?

public class ViewModel
{
    [StringLength(20)]
    public string UserName {get;set;}
}

In the View:

@Html.TextBoxFor(x => x.UserName, new {autocomplete = "off"})

or:

@Html.EditorFor(x => x.UserName)
like image 20
Martin Avatar answered Sep 27 '22 15:09

Martin