- | rssFeed | My book on MSBuild and Team Build | Archives and Categories Tuesday, April 20, 2010

ASP.NET MVC a better TagBuilder

The other day I was working on a site which required a pager, so I searched around a bit and I a pagerby Gunnar Peipman that looked promising. I found a few others but decided against them. Some of them loaded all of the data into memory and then paged from there, and others just flat out didn't work! In any case I had a good experience with Gunnar's. I wanted to take what Gunnar had and create a view helper using my custom view helpers. Along the way I found myself writing some code using the TagBuilderclass that just didn't sit well with me. Take a look at the snippet below which.
TagBuilder startTag = new TagBuilder("a");
startTag.Attributes.Add("href", string.Format("{0}/{1}", this.UrlPrefix, 1));
startTag.Attributes.Add("title", "first page");

TagBuilder previous = new TagBuilder("a");
previous.Attributes.Add("href", string.Format("{0}/{1}", this.UrlPrefix, this.CurrentPage - 1));
previous.Attributes.Add("title", "previous page");
I didn't like the fact that I had to make a bunch of calls to the tag builder to build the HTML for me, it was just uglier than what I wanted. So I decided to create a new tag builder which places an Fluent interface on top of it (ok, maybe its just method chaining). The end result was the FluentTagBuilderclass. I couldn't extend TagBuilderbecause I wanted to change the return types, so instead I created the class to just contain one and to just pass the calls through to it. What I did was to declare all the same properties and methods that the TagBuilder had, but just change the ones who returned void to return the same object itself. So for example I created methods like.
public FluentTagBuilder AddCssClass(string value)
    return this;

public FluentTagBuilder SetInnerHtml(string innerHtml)
    this.TagBuilder.InnerHtml = innerHtml;
    return this;
With this I can chain different method calls together and create code which looks better. If you've used jQuerythen you are used to this. With this in place I was able to convert the snippet above into the following.
FluentTagBuilder startTag =
    new FluentTagBuilder("a")
    .AddAttribute("href", string.Format("{0}/{1}", this.UrlPrefix, 1))
    .AddAttribute("title", "first page");


FluentTagBuilder previous =
    new FluentTagBuilder("a")
    .AddAttribute("href", string.Format("{0}/{1}", this.UrlPrefix, this.CurrentPage - 1))
    .AddAttribute("title", "previous page");

To me this is a lot easier to read, and to create. If you agree you can grab the class and include it in your projects. Links to full source files are below.
  1. FluentTagBuilder.cs
  2. Pager.cs
Sayed Ibrahim Hashimi
ASP.NET MVC | Fluent interface | View helpers Tuesday, April 20, 2010 5:10:14 AM (GMT Daylight Time, UTC+01:00)  #     |