将注释属性添加到自定义HTML帮助器

时间:2018-08-07 14:48:08

标签: data-annotations html-helper asp.net-mvc-5.2

PropertyInfo具有属性(CustomAttributes),该属性返回应用于为其创建html helper的属性的属性。我们如何在助手创建过程中添加另一个注释?例如,对于调用此帮助器的每个属性,我想添加RangeAttribute批注。 目前,我已经完成了以下操作,但是由于未添加注释,因此服务器端验证未进行。

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

0 个答案:

没有答案
相关问题