说我有这样的模型
- public class User
- {
- [required]
- [StringLength(14,ErrorMessage = "Can only be 14 characters long")]
- public string UserName;
- }
我想创建一个这样的Html帮助器:
- @Html.ValidatableEditorFor(m => m.UserName)
所以它会吐出一个正确格式的jQuery Vaidation插件的文本字段,以便能够验证,如下所示:
- <input type="text" class="required" maxlength="14" />
从我的研究中,似乎没有办法迭代MetaDataModel中的所有数据注释,以便我可以检查哪一个适用于jQuery验证.
我如何设想它在伪代码中工作?
- var tag = new TagBuilder("input");
- tag.mergeAttribute("type","text");
- foreach(var attribute in Metadata.attributes)
- {
- CheckForValidatableAttribute(attribute,tag);
- }
- ...
- private void CheckForValidatableAttribute(DataAnnotation attribute,TagBuilder tag)
- {
- switch(attribute.type)
- {
- case required:
- tag.addClass("required");
- break;
- case StringLength
- tag.mergeAttribute("maxlength",attribute.value)
- break;
- }
- }
我该如何去实现这样的帮手?我希望它能够处理数据注释,以便我不必复制验证字面值.
例如,像TextEditorFor这样的当前的Html帮助者将可验证的属性附加到它们的输出字段.它如何做到这一点,以及如何使自己的实现?
干杯
解决方法
你可以使用这个简单的条件:
- if(attribute.Type is ValidationAttribute)
- {
- string className = attribute.Type.Name.Replace("Attribute","").ToLower();
- }
UPDATE
定义一个Html助手:
- public static MvcHtmlString ValidationEditorFor<TModel,TProperty>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel,TProperty>> expression)
- {
- ....
- }
创建这个助手方法:
- private static string GetPropertyNameFromExpression<TModel,TProperty>(HtmlHelper<TModel> htmlHelper,TProperty>> expression)
- {
- MemberExpression memberExpression = expression.Body as MemberExpression;
- if (memberExpression == null)
- throw new InvalidOperationException("Not a memberExpression");
- if (!(memberExpression.Member is PropertyInfo))
- throw new InvalidOperationException("Not a property");
- return memberExpression.Member.Name;
- }
现在在ValidationEditor中使用这个:
- var propertyName = GetPropertyNameFromExpression(htmlHelper,expression);
- var propertyType = typeof(TModel).GetProperties().Where(x=>x.Name == propertyName).First().PropertyType;
- var attributes = propertyType.GetCustomAttributes(true).OfType<ValidationAttribute>();
现在你可以检查属性….休息很容易.