title: How to create MVC HtmlHelper table from list of objects
body: <p>I am trying to create a specific HtmlHelper table extension to reduce the spaghetti code in my View.</p>
  
  <p>Taking a list of domain objects I would like to display a table that is a little bit more intelligent in using the properties of the domain object as columns. In addition, I would like to disable showing of some properties as columns. An idea would be to decorate properties with attributes that tell it not to be shown.</p>
  
  <p>Hopefully that makes sense but here's where I got to so far...</p>
  
  <pre><code>public static string MyTable(this HtmlHelper helper, string name, 
      IList&lt;MyObject&gt; items, object tableAttributes)
  {
      if (items == null || items.Count == 0)
          return String.Empty;
  
      StringBuilder sb = new StringBuilder();
      BuildTableHeader(sb, items[0].GetType());
  
      //TODO: to be implemented...
      //foreach (var i in items)
      //    BuildMyObjectTableRow(sb, i);
  
      TagBuilder builder = new TagBuilder("table");
      builder.MergeAttributes(new RouteValueDictionary(tableAttributes));
      builder.MergeAttribute("name", name);
      builder.InnerHtml = sb.ToString();
  
      return builder.ToString(TagRenderMode.Normal);
  }
  
  private static void BuildTableHeader(StringBuilder sb, Type p)
  {
      sb.AppendLine("&lt;tr&gt;");
  
      //some how here determine if this property should be shown or not
      //this could possibly come from an attribute defined on the property        
      foreach (var property in p.GetProperties())
          sb.AppendFormat("&lt;th&gt;{0}&lt;/th&gt;", property.Name);
  
      sb.AppendLine("&lt;/tr&gt;");
  }
  
  //would be nice to do something like this below to determine what
  //should be shown in the table
  [TableBind(Include="Property1,Property2,Property3")]
  public partial class MyObject
  {
     ...properties are defined as Linq2Sql
  }
  </code></pre>
  
  <p>So I was just wondering if anyone had any opinions/suggestions on this idea or any alternatives?</p>