ASP.NET MVC 3 - 数据Generated注释和最大长度/尺寸对文本框渲染 [英] ASP.NET MVC 3 - Data Annoation and Max Length/Size for Textbox Rendering

查看:130
本文介绍了ASP.NET MVC 3 - 数据Generated注释和最大长度/尺寸对文本框渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道剃刀上查看文件,我们可以做这样的事情
@ Html.TextBox(用户名,空,新的{最大长度= 20,自动完成=关闭})

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

不过,我希望能创建一个模型与明确定义的大小和文本框的最大长度,可用于创建表单的MVC。我尝试[StringLength(N)]对模型的属性之上,但似乎只能做验证ratherh设置文本框的大小。

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.

推荐答案

下面是一个使用 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);
}

这篇关于ASP.NET MVC 3 - 数据Generated注释和最大长度/尺寸对文本框渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆