MaxLength 属性不生成客户端验证属性 [英] MaxLength Attribute not generating client-side validation attributes
问题描述
我对 ASP.NET MVC3 客户端验证有一个奇怪的问题.我有以下课程:
公共类仪器:BaseObject{公共 int Id { 获取;放;}[必填(ErrorMessage = "姓名是必填项.")][MaxLength(40, ErrorMessage = "名称不能超过 40 个字符.")]公共字符串名称 { 获取;放;}}
在我看来:
@Html.EditorFor(model => model.Name)@Html.ValidationMessageFor(model =>model.Name)
这是我为该字段的文本框生成的 HTML:
<input class="text-box single-line" data-val="true" data-val-required="名称为必填项."id="Name" name="Name" type="text" value="">
没有 MaxLengthAttribute
的迹象,但其他一切似乎都在工作.
知道出了什么问题吗?
尝试使用 [StringLength]
属性:
[Required(ErrorMessage = "Name is required.")][StringLength(40, ErrorMessage = "名称不能超过 40 个字符.")]公共字符串名称 { 获取;放;}
这是为了验证目的.例如,如果您想在输入上设置 maxlength 属性,您可以将自定义数据注释元数据提供程序编写为 显示在这篇文章并自定义默认模板.
I have a curious problem with ASP.NET MVC3 client-side validation. I have the following class:
public class Instrument : BaseObject
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required.")]
[MaxLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
}
From my view:
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
And here's the generated HTML I get for the textbox for this field:
<input class="text-box single-line" data-val="true" data-val-required="Name is required." id="Name" name="Name" type="text" value="">
No sign of the MaxLengthAttribute
, but everything else seems to be working.
Any ideas what's going wrong?
Try using the [StringLength]
attribute:
[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
That's for validation purposes. If you want to set for example the maxlength attribute on the input you could write a custom data annotations metadata provider as shown in this post and customize the default templates.
这篇关于MaxLength 属性不生成客户端验证属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!