从DataAnnotations StringLength在Asp.Net MVC文本框的maxlength属性 [英] maxlength attribute of a text box from the DataAnnotations StringLength in Asp.Net MVC

查看:268
本文介绍了从DataAnnotations StringLength在Asp.Net MVC文本框的maxlength属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个应用程序MVC2,并要设置的文字输入的最大长度属性。

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

我已经定义使用​​数据注解的模型对象上stringlength属性,它是正确验证输入的字符串的长度。

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片段:

从型号:

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

在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?

推荐答案

我不知道任何方式实现这一目标,而不诉诸反思。你可以写一个辅助方法:

I am not aware of any way to achieve this without resorting to reflection. You could write a helper method:

public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression, 
    object htmlAttributes
)
{
    var member = expression.Body as MemberExpression;
    var stringLength = member.Member
        .GetCustomAttributes(typeof(StringLengthAttribute), false)
        .FirstOrDefault() as StringLengthAttribute;

    var attributes = (IDictionary<string, object>)new RouteValueDictionary(htmlAttributes);
    if (stringLength != null)
    {
        attributes.Add("maxlength", stringLength.MaximumLength);
    }
    return htmlHelper.TextBoxFor(expression, attributes);
}

,你可以使用这样的:

which you could use like this:

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

这篇关于从DataAnnotations StringLength在Asp.Net MVC文本框的maxlength属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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