Validation 在MVC2中使用DataAnnotation时,是否有一种显示所需字段指示器的好方法?

Validation 在MVC2中使用DataAnnotation时,是否有一种显示所需字段指示器的好方法?,validation,asp.net-mvc-2,data-annotations,Validation,Asp.net Mvc 2,Data Annotations,我已经在所有模型上使用DataAnnotation进行了验证,但我希望在页面加载中显示必填字段的指示符。由于我已将所有验证集中化,因此我不希望在视图中使用硬代码指示符。在加载时调用validation将显示验证摘要。是否有人找到了一种让模型确定所需内容的好方法,但在渲染视图时检查它,类似于Html.ValidationMessageFor?您可以添加一个渲染方法,使用反射来检查字段上的所需属性。这是我不知道的,但应该可以让您开始: public static MvcHtmlString IsRe

我已经在所有模型上使用DataAnnotation进行了验证,但我希望在页面加载中显示必填字段的指示符。由于我已将所有验证集中化,因此我不希望在视图中使用硬代码指示符。在加载时调用validation将显示验证摘要。是否有人找到了一种让模型确定所需内容的好方法,但在渲染视图时检查它,类似于
Html.ValidationMessageFor

您可以添加一个渲染方法,使用反射来检查字段上的所需属性。

这是我不知道的,但应该可以让您开始:

public static MvcHtmlString IsRequiredTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
{
   if (expression.IsRequired())
      return MvcHtmlString.Create(string.Format("{0} [REQUIRED]", helper.TextBoxFor(expression)));

   return helper.TextBoxFor(expression);
}

public static bool IsRequired<T, V>(this Expression<Func<T, V>> expression)
{
   var memberExpression = expression.Body as MemberExpression;
   if (memberExpression == null)
      throw new InvalidOperationException("Expression must be a member expression");

   return memberExpression.Member.GetAttribute<RequiredAttribute>() != null;
}

public static T GetAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
   var attributes = provider.GetCustomAttributes(typeof(T), true);
   return attributes.Length > 0 ? attributes[0] as T : null;
}
public static MvcHtmlString IsRequiredTextBoxFor(此HtmlHelper,表达式)
{
if(expression.IsRequired())
返回MvcHtmlString.Create(string.Format(“{0}[REQUIRED]”,helper.TextBoxFor(expression));
返回helper.TextBoxFor(表达式);
}
需要公共静态布尔值(此表达式)
{
var memberExpression=expression.Body作为memberExpression;
if(memberExpression==null)
抛出新的InvalidOperationException(“表达式必须是成员表达式”);
返回memberExpression.Member.GetAttribute()!=null;
}
公共静态T GetAttribute(此ICustomAttributeProvider提供程序),其中T:Attribute
{
var attributes=provider.GetCustomAttributes(typeof(T),true);
返回属性。长度>0?属性[0]为T:null;
}

有一段时间我被拉到了另一个项目上,所以我没有机会尝试这个,但看起来至少是一个好的开始。谢谢