MVC3 - Get Data Attribute in html.helper

2019-07-20 07:43发布

问题:

I'm trying to create a custom attribute to control formatting in a custom HTML helper object. The source code for my custom selector class is (Code is from http://forums.asp.net/t/1649193.aspx/1/10).

        public static MvcHtmlString DdUovFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel, IDictionary<string, object> htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        var m = expression.Body.GetType();

        IDictionary<string, object> validationAttributes = htmlHelper
            .GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);

        if (htmlAttributes == null)
            htmlAttributes = validationAttributes;
        else
            htmlAttributes = htmlAttributes.Concat(validationAttributes).ToDictionary(k => k.Key, v => v.Value);

        return SelectExtensions.DropDownListFor(htmlHelper, expression, 
               selectList, optionLabel, htmlAttributes);
    }

My custom attribute is

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | 
      AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class LookUpAttribute : Attribute
{
    public LookUpAttribute(Type providerName)
    {
        this.providerName = providerName;
    }
    protected ILookup providerName;
}

My problem is that I cannot figure out how to retrieve my custom attribute in in the HTML helper method.

回答1:

The best way to achieve this is for your attribute to implement IMetadataAware. In the implementation of the OnMetadataCreated method you should add values to the metadata.AdditionalValues dictionary. You can then retrieve the value in your helper or wherever else you have access to ModelMetadata.

Note that this solution is prefered because it does not actually encode any information about the fact that your metadata is driven by attributes.