Simple Table Control in ASP.NET MVC

Posted in Development on Saturday, Saturday, October 18, 2008 by Anthony Burns

I'm digging the new ASP.NET MVC framework. Big style. Transitioning from classic ASP to ASP.NET left me a bit frustrated with the abstraction introduced. It was supposed to be better for us developers that the stateless nature of HTTP was being hidden away, that the framework would take care of all the state management, leaving us time to eat pizza and drink beer; but that just left me fat and drunk. Thankfully I can now dive back into having full control of my html and post data, among other things, by using MVC.

However, I don't want to hand craft every single piece of html every time, and there's a lot of things day to day that I just want rendering without a lot of effort - tables being one of them, so I set about building a simple but relatively powerful table control.

Requirements: I wanted the table to render an IEnumerable I might pull straight from a Linq query to a html table; including the ability to make each row a link, to highlight a selected row and the facility to add columns to the end of the table containing action links such as "Delete".

After Googling 'asp net mvc controls' I discovered a few different ways of creating and rendering controls under the MVC framework. I finally opted to write an extension method to the HtmlHelper class, made available through the Html property on each MVC View.

Since this probably won't be the last control I'll build, I created an interface each control could implement:

interface ISimpleControl {
    string Render(HtmlHelper helper)
}

I then created a small HtmlHelper extension method to render these simple controls:

public static string RenderControl(this HtmlHelper helper, ISimpleControl control)
{
    return control.Render(helper);
}

I can now render any simple control using:

<%=Html.RenderControl(new MyFirstControl());%>

Because my datasource could be any type of object returned from a Linq query (including anonymous types) I have to use reflection to discover the properties of these objects in order to render the columns of the table. I opted to do this as soon as the data source is set and convert it to a DataTable for easy traversal when it comes to rendering the html:

private static DataTable GetDataTableFromIEnumerable(IEnumerable dataSource)
{
    // Since IEnumerable doesn't expose an indexer to get the first element
    object obj;
    foreach (object o in data)
    {
        obj = o;
        break;
    }
    if (obj == null) return null;

    DataTable dataTable = new DataTable();

    // Use reflection to create DataColumns for each of the properties in the object
    Type type = obj.GetType();
    PropertyInfo[] propertyInfo = type.GetProperties();
    string[] keys = new string[propertyInfo.Length];
    for (int i = 0; i < keys.Length; i++)
    {
        DataColumn column = new DataColumn(propertyInfo[i].Name, typeof(string));
        dataTable.Columns.Add(column);
        keys[i] = propertyInfo[i].Name;
    }

    // Iterate through the IEnumerable and populate the DataTable from
    // each object using Reflection
    foreach (object row in dataSource)
    {
        DataRow dataRow = dataTable.NewRow();
        foreach (DataColumn column in dataTable.Columns)
        {
            object result = type.InvokeMember(column.ColumnName, BindingFlags.GetProperty, 
                                              null, row, null);
            if (result != null)
            {
        	dataRow[column] = result.ToString();
            }
        }
        dataTable.Rows.Add(dataRow);
    }

    return dataTable;
}

The first thing I do is to get the first element in the IEnumerable to perform the reflection on. Since IEnumerables don't expose an indexer, the only way I could think to do this is by performing a foreach loop and exiting as soon as I have a copy of the first element. I then get a list of the properties exposed by the object and create matching DataColumns for the DataTable. The second foreach loop populates a DataRow from each object and appends it to the table.

It's highly probable that I'll make other controls that iterate over IEnumerable data sources in this manner further down the road, so I opted to extract this functionality into an abstract base class called DataControl. This control exposes a public DataSource property for setting the IEnumerable, which converts it into a DataTable available to any derived classes through a protected property:

public abstract class DataControl : ISimpleControl
{
    protected DataTable DataTable { get; set; }

    public IEnumerable DataSource
    {
        set
        {
            DataTable = GetDataTableFromIEnumerable(value);
        }
    }

...

}

A derived class could then be used with an IEnumerable from your ViewData like so:

<%=Html.RenderControl(new MyDataControl{ DataSource = (IEnumerable)ViewData["MyLinqResult"] });%>

All that's left to do is to inherit from that DataControl and override the Render method to render the html:

public override string Render(HtmlHelper helper)
{
    if (DataTable == null) return "";

    // Use either the columns requested, or all table columns if not specified
    string[] keys = DisplayColumns ?? GetColumnKeys(DataTable);

    StringBuilder header = new StringBuilder();

    // Build the html for the table's header
    header.AppendLine("  <tr>");
    foreach (string key in keys)
    {
        header.AppendLine("    <th>" + key + "</th>");
    }
    header.AppendLine("  </tr>");

    bool altRow = true;
    StringBuilder data = new StringBuilder();

    // Render the relevant Html for each Row in the table
    foreach (DataRow row in DataTable.Rows)
    {
        // Add an 'Alt' Css class to alternating rows
        string rowClass = altRow ? "Alt" : "";

        data.AppendLine("  <tr class=\"" + rowClass + "\">");

        // Render the Html for each column of this row 
        foreach (string key in keys)
        {
            data.AppendLine("    <td>" + row[key] + "</td>");
        }

        data.AppendLine("  </tr>");

        // Switch whether or not this is an alternating row
        altRow = altRow ? false : true;
    }

    // Piece together all of the Html and return it
    StringBuilder html = new StringBuilder();
    html.AppendLine("<table>");
    html.Append(header);
    html.Append(data);
    html.AppendLine("</table>");

    return html.ToString();
}

I've also added a DisplayColumns property of type string[] to the Table class that enables me to specify the columns to render, as I might not want to render all of the properties. In line 6 I check for the existence of this property and if it hasn't been set I call GetColumnKeys() which is a private method I've written that returns a string[] of the DataColumn names from the DataTable.

I then render the html for the table header, and follow that up by rendering each row from the DataTable. I add an "Alt" class to each alternating row so I can use Css to colour the alternating rows differently.

I can now render a table in my View with a single line of code:

<%=Html.RenderControl(new Table{ DisplayColumns = new string[] { "Name", "EMail" }, 
                                 DataSource = (IEnumerable)ViewData["MyLinqResult"] });%>

I'll finish this control in the next article by adding the functionality to click a row to fire an action, highlight a selected row, and include further actions in additional columns at the end of the table.

You can download the full source code from this article here: MvcTableControl.zip

Tagged as: asp.net, c#, mvc

Comments

Pedro spoke on Monday, Monday, April 13, 2009

A beautiful piece of code. Thanks

ITJOBLOG spoke on Wednesday, Wednesday, April 15, 2009

Thanks for this nice post. Very informative ! I've been playing with ASP.NET MVC recently, and it is a delight. Yes, there is more manual coding than with Web Forms, but it is worth it for the additional control you gain.

Matt Slay spoke on Sunday, Sunday, February 14, 2010

Post a screenshot sample, man.