我正在开发一个MVC2应用程序,希望设置文本输入的最大长度属性。
我已经使用数据注释在Model对象上定义了string length属性,并且它正在验证输入的字符串的长度是否正确。
我不想在模型已经有信息时,通过手动设置max length属性,在我的视图中重复相同的设置。有没有办法做到这一点?
下面是代码片段:
从模型中:
[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"/>有没有办法做到这一点?
发布于 2010-03-05 20:00:40
我不知道有什么方法可以在不进行反思的情况下实现这一点。你可以写一个helper方法:
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" })%>发布于 2012-03-15 04:45:39
如果你正在使用非侵入性的验证,你也可以处理这个客户端:
$(document).ready(function ()
{
$("input[data-val-length-max]").each(function ()
{
var $this = $(this);
var data = $this.data();
$this.attr("maxlength", data.valLengthMax);
});
});发布于 2013-11-20 01:18:06
虽然我个人很喜欢jrummel的jquery修复,但这里有另一种在你的模型中保持单一真理源的方法……
不是很漂亮,但是..工作正常。对我来说..。
我没有使用属性修饰,而是在我的模型库/dll中定义了一些命名良好的公共常量,然后通过HtmlAttributes在我的视图中引用它们,例如
Public Class MyModel
Public Const MAX_ZIPCODE_LENGTH As Integer = 5
Public Property Address1 As String
Public Property Address2 As String
<MaxLength(MAX_ZIPCODE_LENGTH)>
Public Property ZipCode As String
Public Property FavoriteColor As System.Drawing.Color
End Class然后,在剃刀视图文件中,在EditorFor中...在重载中使用HtmlAttirubte对象,提供所需的最大长度属性并引用常量。您必须通过完全限定的名称空间路径提供常量...MyCompany.MyModel.MAX_ZIPCODE_LENGTH..因为它不会直接挂在模型上,但是,它是有效的。
https://stackoverflow.com/questions/2386365
复制相似问题