I have 1 base model, a child model and another which is a child of the second one:
class FirstModel
{
public virtual decimal? Property1 { get; set; }
}
class SecondModel : FirstModel
{
public override decimal? Property1 { get; set; }
}
class ThirdModel : SecondModel
{
[RequiredIfSubmitting]
public override decimal? Property1 { get; set; }
}
RequiredIfSubmitting
extends BaseRequiredAttribute
I am writing a custom label for my view:
public static MvcHtmlString LabelForCustom<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes = null)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var member = expression.Body as MemberExpression;
if (member != null)
{
// Does it have the required attribute?
var isRequired = Attribute.GetCustomAttributes(member.Member, typeof(RequiredAttribute), false).Any();
if (!isRequired)
{
metadata.IsRequired = Attribute.GetCustomAttributes(member.Member, typeof(BaseRequiredAttribute), true).Any();
}
}
}
I am trying to get attributes for ThirdModel.Property1.
The problem is that when the reuired/requiredifsubmitting attribute is not visible for GetCustomAttributes method - it comes as none - metadata.IsRequired is set to false as result.
Unless I put the attributes in FirstModel Property1 then metadata.IsRequired is set to true.
I cannot put the attributes in the upper model classes because other models inherit from them which do not necessary have mandatory derived properties.
How to force GetCustomAttributes to see attributes of lower level model property?
Thanks