Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get Custom Attribute Value in MVC3 HTML Helper

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"];
        }
like image 975
Jeff Reddy Avatar asked Oct 28 '11 14:10

Jeff Reddy


1 Answers

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"];
like image 180
Darin Dimitrov Avatar answered Sep 26 '22 15:09

Darin Dimitrov