ASP.NET MVC 3 - 数据处理和文本框渲染的最大长度/大小

fro*_*oxx 8 data-annotations razor asp.net-mvc-3

我知道在Razor View文件中,我们可以做这样的事情@Html.TextBox("username",null,new {maxlength = 20,autocomplete ="off"})

但是,我希望为MVC创建一个模型,该模型可用于创建一个明确定义文本框大小和最大长度的表单.我在模型的属性上尝试[StringLength(n)],但这似乎只进行验证而不是设置文本框的大小.

无论如何,我们可以将文本字段的长度定义为模型属性顶部的数据注释吗?

因此,最终,我们可以通过使用razor映射到模型来创建整个表单,而不是逐个明确地拾取模型属性以设置文本框大小.

Era*_*nga 14

以下是使用的自定义帮助程序的概述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);
}
Run Code Online (Sandbox Code Playgroud)