Can't get Custom Attribute Value in MVC3 HTML Helper

£可爱£侵袭症+ 提交于 2019-12-21 05:05:23

问题


I've extended the HTML helper with a method that needs an attribute value from the property of the model. So I've defined a custom attribute as such.

    public class ChangeLogFieldAttribute : Attribute {
        public string FieldName { get; set; }
    }

It's used like this in my model.

    [Display(Name = "Style")]
    [ChangeLogField(FieldName = "styleid")]
    public string Style { get; set; }

In my helper method, I've got the following code to get the FieldName value of my attribute, if the attribute is used for the property.

        var itemName = ((MemberExpression)ex.Body).Member.Name;

        var containerType = html.ViewData.ModelMetadata.ContainerType;
        var attribute = ((ChangeLogFieldAttribute[])containerType.GetProperty(html.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(ChangeLogFieldAttribute), false)).FirstOrDefault();
        if (attribute != null) {
            itemName = attribute.FieldName;
        }

However, when I reach this code, I get an exception because the containerType is null.

I'm not sure if I'm doing any of this correct, but I pulled from about 4 different sources to get this far. If you could suggest a fix to my problem or an alternative, I'd be grateful.

Thanks.

UPDATE WITH SOLUTION

I used Darin Dimitrov's solution, although I had to tweak it some. Here is what I added. I had to check for the existence of the attribute metatdata and all was good.

        var fieldName = ((MemberExpression)ex.Body).Member.Name;

        var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
        if (metadata.AdditionalValues.ContainsKey("fieldName")) { 
            fieldName = (string)metadata.AdditionalValues["fieldName"];
        }

回答1:


You could make the attribute metadata aware:

public class ChangeLogFieldAttribute : Attribute, IMetadataAware
{
    public string FieldName { get; set; }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["fieldName"] = FieldName;
    }
}

and then inside the helper:

var metadata = ModelMetadata.FromLambdaExpression(ex, htmlHelper.ViewData);
var fieldName = metadata.AdditionalValues["fieldName"];


来源:https://stackoverflow.com/questions/7930574/cant-get-custom-attribute-value-in-mvc3-html-helper

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