title: Get Custom Attributes from Lambda Property Expression
body: <p>I am using ASP.NET MVC 2 Preview 2 and have written a custom HtmlHelper extension method to create a label using an expression. The TModel is from a simple class with properties and the properties may have attributes to define validation requirements. I am trying to find out if a certain attribute exists on the property the expression represents in my label method.</p>
  
  <p>The code for the class and label is:</p>
  
  <pre><code>public class MyViewModel
  {
      [Required]
      public string MyProperty { get; set; }
  }
  
  public static MvcHtmlString Label&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, string label)
  {
      return MvcHtmlString.Create(string.Concat("&lt;label for=\"", expression.GetInputName(), "\"&gt;", label, "&lt;/label&gt;"));
  }
  
  public static string GetInputName&lt;TModel, TProperty&gt;(this Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression)
  {
      return expression.Body.ToString().Substring(expression.Parameters[0].Name.Length + 1);
  }
  </code></pre>
  
  <p>Then I would call the label like this:</p>
  
  <pre><code>Html.Label(x =&gt; x.MyProperty, "My Label")
  </code></pre>
  
  <p>Is there a way to find out if the property in the expression value passed to the Label method has the Required attribute?</p>
  
  <p>I figured out that doing the following does get me the attribute if it exists, but I am hopeful there is a cleaner way to accomplish this.</p>
  
  <pre><code>public static MvcHtmlString Label&lt;TModel, TProperty&gt;(this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, string label)
  {
      System.Attribute.GetCustomAttribute(Expression.Property(Expression.Parameter(expression.Parameters[0].Type, expression.GetInputName()), expression.GetInputName()).Member, typeof(RequiredAttribute))
  
      return MvcHtmlString.Create(string.Concat("&lt;label for=\"", expression.GetInputName(), "\"&gt;", label, "&lt;/label&gt;"));
  }
  </code></pre>