DCSIMG
Extending ASP.NET MVC HtmlHelper Class - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Extending ASP.NET MVC HtmlHelper Class

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

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# January 13, 2009 3:43 PM

ASP.NET MVC Archived Blog Posts, Page 1 said:

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# January 13, 2009 5:52 PM

cypher said:

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

# January 14, 2009 2:24 PM

Extending ASP.NET MVC HtmlHelper Class - Gil Fink on .Net said:

Pingback from  Extending ASP.NET MVC HtmlHelper Class - Gil Fink on .Net

# January 14, 2009 4:01 PM

Gil Fink said:

@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.

# January 22, 2009 9:27 AM

Evan Freeman said:

Why make it take IList instead of IEnumerable?

# March 9, 2009 9:03 PM

francis said:

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

# March 10, 2009 2:20 AM

Gil Fink said:

@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.

# March 10, 2009 8:49 AM

Gil Fink said:

@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: stephenwalther.com/.../chapter-6-understanding-html-helpers.aspx

# March 10, 2009 8:53 AM

郁闷的翩翩 said:

原文地址:ExtendingASP.NETMVCHtmlHelperClass在这篇帖子中我会使用一个示例演示扩展ASP.NETMVCHtmlHelper类,让它们可以在你的MVC视图中...

# March 10, 2009 3:09 PM

Dan Sylvester said:

Thanks,

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

# March 10, 2009 4:03 PM

Thanigainathan.S said:

Hi,

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

Thanks,

Thani

# March 11, 2009 1:23 PM

Gil Fink said:

@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).

# March 11, 2009 2:44 PM

C#| [C#]??????ASP.NET MVC HtmlHelper??? | Mikel said:

Pingback from  C#|  [C#]??????ASP.NET MVC HtmlHelper??? | Mikel

# March 5, 2010 2:01 AM

Fred Mastropasqua said:

Extending the ASP.NET MVC HtmlHelper in VB.NET Specifically

# October 23, 2010 9:37 PM

Development In Greece said:

Extending ASP.NET MVC HtmlHelper Class

# December 31, 2010 4:44 PM

Expand asp.net MVC HtmlHelper class (turn) said:

Pingback from  Expand asp.net MVC HtmlHelper class (turn)

# June 10, 2011 9:07 AM

ASP.NET MVC 3 Css & Js Otomatik Versiyonlama | HaKoSe | Web Developer said:

Pingback from  ASP.NET MVC 3 Css &amp; Js Otomatik Versiyonlama | HaKoSe | Web Developer

# March 21, 2012 2:01 PM

ASP.NET MVC 3 Css & Js Otomatik Versiyonlama said:

Pingback from  ASP.NET MVC 3 Css &amp; Js Otomatik Versiyonlama

# April 6, 2012 10:25 AM

How to create MVC HtmlHelper table from list of objects | C Language Development | C Programming Language Tutorial said:

Pingback from  How to create MVC HtmlHelper table from list of objects | C Language Development | C Programming Language Tutorial

# March 1, 2013 2:57 AM