views:

68

answers:

2

I've got validation working with DataAnnotations on all my models, but I'd like to display an indicator for required fields on page load. Since I've got all my validation centralized, I'd rather not hard-code indicators in the View. Calling validation on load would show the validation summary. Has anyone found a good way of letting the model determine what's required, but checking it upon rendering the view, similar to Html.ValidationMessageFor?

A: 

You could add a render method that uses reflection to check for the Required attribute on the field.

GalacticCowboy
A: 

This is off the top of my head, but it should get you started:

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;
}
mxmissile
I got yanked off onto another project for a while, so I haven't had the opportunity to try this, but it looks like at least a good start. Thanks!
Jeremy Gruenwald