The PropertyInfo
has a property (CustomAttributes
) which returns the attributes applied to the property for which html helper is being created. How do we add another annotation during the helper creation? For example, for every property on which this helper is called, I want to add the RangeAttribute
annotation.
Currently, I have done the following, but the server side validation is not happening since the annotation is not being added.
public static MvcHtmlString DateTimeWithIntervalFor<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes = null, string format = "{0:yyyy-MM-dd hh:mm:ss tt}")
{
var routeValueDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
var metadata = HtmlHelperExtensions.GetModelMetadata(helper, expression);
var propertyInfo = HtmlHelperExtensions.GetModelPropertyInfoFromMetadata(metadata);
RangeAttribute rangeAttribute = propertyInfo.GetCustomAttributes(typeof(RangeAttribute), false).FirstOrDefault() as RangeAttribute;
if (rangeAttribute != null)
{
AddMinimumAndMaximumAttributeValues(routeValueDictionary, rangeAttribute.Minimum, rangeAttribute.Maximum);
}
else
{
var minimumValue = new DateTime(2000, 1, 1);
var maximumValue = new DateTime(2018, 1, 1);
string formattedMinimumValue = string.Format(format, minimumValue);
string formattedMaximumValue = string.Format(format, maximumValue);
/* This is where I am struggling, I have tried setting the attribute
* using SetCustomAttribute, but it isn't accessible/defined on
* PropertyInfo.
* What I have done currently doesn't work too.
*/
metadata.AdditionalValues.Add("RangeAttribute", new RangeAttribute(typeof(RangeAttribute), formattedMinimumValue, formattedMaximumValue));
/*
* This is for adding client side attributes, which work fine with
* jQuery Validation, but since the annotation is not added to the
* property, on the server ModelState is valid, even if the value
* doesn't fall in the range.
*/
AddMinimumAndMaximumAttributeValues(
routeValueDictionary, formattedMinimumValue, formattedMaximumValue
);
}
return helper.TextBoxFor(expression, format, routeValueDictionary);
}