Extending ASP.NET MVC HtmlHelper Class

January 13, 2009

Extending ASP.NET MVC HtmlHelper Class


In the post I’ll showExtending ASP.NET MVC HtmlHelper Class
an example of how
to extend the
ASP.NET MVC
HtmlHelper class
that you can use
within your MVC
views. In the example I’ll provide a simple solution for building an Html table.


The HtmlHelper class


The HtmlHelper class is a class that can be used within ASP.NET MVC
framework in order to help us render Html fragments of views.
The class is provided with a lot of methods that can help you render Html
types (textboxes, checkboxes etc) or Html parts (<form> for example).
The ASP.NET MVC framework helpers are currently the following:



  • Html.ActionLink()

  • Html.BeginForm()

  • Html.CheckBox()

  • Html.DropDownList()

  • Html.EndForm()

  • Html.Hidden()

  • Html.ListBox()

  • Html.Password()

  • Html.RadioButton()

  • Html.TextArea()

  • Html.TextBox()

For example if I would like to render a checked checkbox with the name
myChkbox I can do it like that in my view:



<%= Html.CheckBox(“myChkbox”, true) %> 

All the Html helpers are built as extension methods and can be located in
the System.Web.Mvc.Html namespace for review (if you like).


Building Html Table Extension For HtmlHelper


In my example I wrote an extension method for HtmlHelper to supply the
Html table rendering method. The example is supplied as is and you can
modify it or build your own example of how to render an Html table:



public static class MVCHelpers
{
    public static string Table(this HtmlHelper helper, string name, IList items, IDictionary<string, object> attributes)
    {
        if (items == null || items.Count == 0 || string.IsNullOrEmpty(name))
        {                
            return string.Empty;
        }
        
        return BuildTable(name, items, attributes);            
    }
 
    private static string BuildTable(string name, IList items, IDictionary<string, object> attributes)
    {
        StringBuilder sb = new StringBuilder();
        BuildTableHeader(sb, items[0].GetType());
 
        foreach (var item in items)
        {
            BuildTableRow(sb, item);
        }
 
        TagBuilder builder = new TagBuilder(“table”);
        builder.MergeAttributes(attributes);
        builder.MergeAttribute(“name”, name);
        builder.InnerHtml = sb.ToString();            
        return builder.ToString(TagRenderMode.Normal);
    }
 
    private static void BuildTableRow(StringBuilder sb, object obj)
    {
        Type objType = obj.GetType();
        sb.AppendLine(“\t<tr>”);
        foreach (var property in objType.GetProperties())
        {
            sb.AppendFormat(“\t\t<td>{0}</td>\n”, property.GetValue(obj, null));
        }
        sb.AppendLine(“\t</tr>”);
    }
 
    private static void BuildTableHeader(StringBuilder sb, Type p)
    {
        sb.AppendLine(“\t<tr>”);
        foreach (var property in p.GetProperties())
        {
            sb.AppendFormat(“\t\t<th>{0}</th>\n”, property.Name);
        }
        sb.AppendLine(“\t</tr>”);
    }
}

As you can see I’m extending the HtmlHelper with an extension method
that is called Table. The main function to render a table is the BuildTable
method that uses the ASP.NET MVC TagBuilder class in order to build the
table tag. You can also see that in my example I use reflection to get the
properties of the list of items I get and I use those properties as my
header and their values as the values of the table cells.


Using the Html Table Extension In a View


If you want to use the new custom Html helper for table that I showed
earlier you should do the following:



  • Register the namespace of the new helper in the view using
    the import tag in the view’s head like that:

    <%@ Import Namespace=“TaskList.Models” %>

  • Use the Html property of the view with the new Table method.
    For example the following line will add an Html table with the name
    myTable and the current model of the view:

    <%= Html.Table(“myTable”, (IList)ViewData.Model, null) %>  
    Pay attention that if the Model isn’t IList you’ll get an exception.

Summary


Lets sum up, in today’s post I introduced the HtmlHelper class and
showed how to build a simple extension for that class. There is another way
to extend the HtmlHelper class by building your  own class (for example
TableHelper) and all you have to do is to build methods that return the rendered
html to be added to the view. The use of extension method is easier in my opinion.


DotNetKicks Image

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

9 comments

  1. cypherJanuary 14, 2009 ב 14:24

    Thanks for sharing. A working and downloadable app would be even more helpful.

    Reply
  2. Gil FinkJanuary 22, 2009 ב 9:27

    @cypher,
    Thanks for the comment. You can copy the code I wrote to a class in your MVC Framework project and start working with it as described in the post.

    Reply
  3. Evan FreemanMarch 9, 2009 ב 21:03

    Why make it take IList instead of IEnumerable?

    Reply
  4. francisMarch 10, 2009 ב 2:20

    it seems we need more work if we want to display a gridview like traditional aspx page

    Reply
  5. Gil FinkMarch 10, 2009 ב 8:49

    @Evan Freeman,
    I could have used IEnumerable instead of IList. As I wrote “The example is supplied as is and you can
    modify it or build your own example of how to render an Html table”. I agree that in some situations IEnumerable is preferable then IList.

    Reply
  6. Gil FinkMarch 10, 2009 ב 8:53

    @francis,
    Yes. We need a lot of work if we want to display a gridview like traditional aspx page. I suggest to look at Stephen Walther’s example (Creating a DataGrid Helper) in the following link: http://stephenwalther.com/blog/archive/2009/03/03/chapter-6-understanding-html-helpers.aspx

    Reply
  7. Dan SylvesterMarch 10, 2009 ב 16:03

    Thanks,

    This helps alot as I’m still playing catchup with MVC.

    Reply
  8. Thanigainathan.SMarch 11, 2009 ב 13:23

    Hi,

    How can you say that this is better than the normal HTML tables ? Please let me know the advantages.

    Thanks,
    Thani

    Reply
  9. Gil FinkMarch 11, 2009 ב 14:44

    @Thanigainathan,
    The solution is rendering Html tables from the List that is provided to the HtmlHelper’s extension method that I wrote. Its advantage is by supporting the rendering of Html tables instead of writing your Html table using server script tags. The two methods (script tags and my solution) will give the same result (Html table).

    Reply