asp.net-mvc - 可以浏览 DataAnnotations 的自定义 Html 帮助器

标签 asp.net-mvc data-annotations modelmetadata

假设我有一个这样的模型

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

我怎样才能获得这样的助手呢?我希望它能够处理数据注释,这样我就不必重复验证文字。

例如,当前的 Html 帮助程序(如 TextEditorFor)会将可验证的属性附加到其输出字段。它是如何做到这一点的?我该如何实现自己的实现?

干杯

最佳答案

您可以使用这个简单的条件:

if(attribute.Type is ValidationAttribute)
{
   string className = attribute.Type.Name.Replace("Attribute", "").ToLower();
}
<小时/>

更新

定义一个 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, Expression<Func<TModel, 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;
}

现在在 ValidationEditorFor 中使用它:

var propertyName = GetPropertyNameFromExpression(htmlHelper, expression);
var propertyType = typeof(TModel).GetProperties().Where(x=>x.Name == propertyName).First().PropertyType;
var attributes = propertyType.GetCustomAttributes(true).OfType<ValidationAttribute>();

现在您可以检查属性......剩下的很容易。

关于asp.net-mvc - 可以浏览 DataAnnotations 的自定义 Html 帮助器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10381939/

相关文章:

asp.net-mvc - 使用 c# Asp .net MVC 将视频上传到 Youtube

asp.net - ASP.NET MVC 中一个页面中的不同标题,无需创建另一个母版页

c# - 将输入到数据库的电子邮件地址与 DataAnnotations 进行比较

asp.net-mvc-3 - 使用 AutoMapper 将元数据传输到 View 模型的技术

asp.net-mvc-3 - 使用 AutoMapper 将元数据传输到 View 模型的技术

c# - 在映射中首先使用不同的属性名称从 Entity Framework 6 数据库中的数据库中获取列名称

c# - MVC 5、EF 6 和多行(批量)编辑

css - 编写 MVC 3 应用程序时的表单设计方法

c# - MVC 4 中的部分实体类未显示数据注释

c# - Validator.TryValidateProperty 不工作