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

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

问题描述

我正在开发一个 MVC2 应用程序并且想要设置文本输入的 maxlength 属性.

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

我已经使用数据注释在 Model 对象上定义了 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?

以下代码片段:

来自模型:

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

观点:

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

我想避免做的是:

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

我想得到这个输出:

<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);
}

你可以这样使用:

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

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

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