maxlength属性不生成客户端验证属性 [英] MaxLength Attribute not generating client-side validation attributes
问题描述
我有ASP.NET MVC3客户端验证一个奇怪的问题。我有以下类:
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; }
}
这是我的看法:
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
和这里的生成的HTML我得到的文本框此字段:
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="">
在MaxLengthAttribute的迹象,但一切似乎是工作。
No sign of the MaxLengthAttribute, but everything else seems to be working.
任何想法是怎么回事?
推荐答案
尝试使用 [StringLength]
属性:
[Required(ErrorMessage = "Name is required.")]
[StringLength(40, ErrorMessage = "Name cannot be longer than 40 characters.")]
public string Name { get; set; }
这是用于验证。如果你想例如设置输入maxlength属性,你可以写一个自定义数据的元数据的注解提供者<一个href=\"http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-_2D00_-ASP.Net-MVC-2.0-Beta_2D00_1.aspx\">shown在这个岗位和自定义的default模板。
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屋!