Blogging on programming and life in general.

MVC Custom Extension Methods

Posted in: ASP.NET

I've been toying around with MVC for quite some time now. Initially, I couldn't imagine breaking away from the safety-net that is ASP.NET Web Forms. What many developers are not aware of when moving over to the ASP.NET MVC framework is that you have to write everything from scratch. You will not have the comfort of dragging and dropping event driven controls in a GUI-centric way.

But nowadays, I am itching to build new sites in MVC. I like to be in control of the whole page lifecycle and the mark-up that is generated.

Since there are no pre-built resusable controls, I decided start developing my own library of extensions that I could use in future MVC projects I work on. Ranging from pagination to tag clouds.

Creating custom extensions is really easy. I started off by creating a Category Navigation that returns a IHtmlString (HTML-encoded string that should not be encoded again).

public static IHtmlString CategoryNavigation(this WebViewPage wvp)
    StringBuilder navBuilder = new StringBuilder();

    List<CustomCategory> categories = CustomCategoryLogic.GetCategories();

    if (categories.Count > 0)
        navBuilder.Append("<ul class=\"nav\">");
        navBuilder.Append("<li><a href=\"/\">Home</a></li>");

        foreach (CustomCategory cc in categories)
            navBuilder.AppendFormat("<li><a href=\"/{0}\">{1}</a></li>", cc.Slug, cc.Name);


    return MvcHtmlString.Create(navBuilder.ToString());

To display my category navigation in one of my Views, I just need to write:


How easy is that!?

blog comments powered by Disqus