MVC3 - Get Data Attribute in html.helper

最后都变了- 提交于 2020-01-15 02:42:27

问题


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.



来源:https://stackoverflow.com/questions/7693589/mvc3-get-data-attribute-in-html-helper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!