Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create MVC HtmlHelper table from list of objects

I am trying to create a specific HtmlHelper table extension to reduce the spaghetti code in my View.

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.

Hopefully that makes sense but here's where I got to so far...

public static string MyTable(this HtmlHelper helper, string name, 
    IList<MyObject> 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("<tr>");

    //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("<th>{0}</th>", property.Name);

    sb.AppendLine("</tr>");
}

//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
}

So I was just wondering if anyone had any opinions/suggestions on this idea or any alternatives?

like image 444
David Avatar asked Dec 11 '09 22:12

David


2 Answers

Looks good so far, but Gil Fink may have already done the work for you here: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/01/13/extending-asp-net-mvc-htmlhelper-class.aspx

like image 178
Robert Harvey Avatar answered Sep 28 '22 07:09

Robert Harvey


I strongly suggest to use MvcContrib's Grid. If you decide not to, at least you can take a look at how they solved the table generation interface problem.

like image 41
queen3 Avatar answered Sep 28 '22 06:09

queen3