title: Can't get Custom Attribute Value in MVC3 HTML Helper
body: <p>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.</p>
  
  <pre><code>    public class ChangeLogFieldAttribute : Attribute {
          public string FieldName { get; set; }
      }
  </code></pre>
  
  <p>It's used like this in my model.</p>
  
  <pre><code>    [Display(Name = "Style")]
      [ChangeLogField(FieldName = "styleid")]
      public string Style { get; set; }
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>        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;
          }
  </code></pre>
  
  <p>However, when I reach this code, I get an exception because the containerType is null.</p>
  
  <p>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.</p>
  
  <p>Thanks.</p>
  
  <p><strong>UPDATE WITH SOLUTION</strong></p>
  
  <p>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.</p>
  
  <pre><code>        var fieldName = ((MemberExpression)ex.Body).Member.Name;
  
          var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
          if (metadata.AdditionalValues.ContainsKey("fieldName")) { 
              fieldName = (string)metadata.AdditionalValues["fieldName"];
          }
  </code></pre>