ReBuildAll Blog
Thoughts (mostly) on .NET development

Extending ASP.NET MVC HtmlHelper and Gravatars   (MVC)   
I got excited about Gravatars the other day and decided to add support for them into my blog. You can read more about Gravatars and how they can be used in your project on the following page:


Having used ASP.NET MVC, the view that was displaying the comments had something like the following in them. This displayed the name of the commenter being a hyperlink, and that pointing to a mailto: link with the email address. The address was applied some transformations to prevent spammers from picking them from the page automatically:

<%= Html.Encode ( SomeBlogNamespace.SpamFreeEmail ( Model.Comment.CommentedEmail ) )%>

Now I did not want to change the model at all, but still wanted to add support for Gravatars. For this, I needed a method that could calculate the MD5 hash and display it in the format Gravatar wants it.

As I have my own base classes and model classes, I could have added the code there but decided to extend the MVC HtmlHelper instead. Using extension methods, that is really simple. I just added a new class to hold my extension method:

    public static class GravatarHelper
        public static string GravatarHash ( this HtmlHelper html, string value )
            var byteArray =
                   MD5CryptoServiceProvider.Create ().ComputeHash (
                        System.Text.ASCIIEncoding.ASCII.GetBytes ( value.ToLower () ) );

            string result = string.Empty;
            foreach ( var item in byteArray )
                result += item.ToString ( "x2" );

            return result;

I also needed to add a namespace import into the .ASCX file that contained my comments view:

<%@ Import Namespace="namespace" %>

After that I could change the view to display the picture from Gravatar by calculating the hash from within the view code:

        <%= Html.GravatarHash ( Model.Comment.CommentedEmail ) %>

If you make a comment into this blog now, you can take advantage of Gravatars by giving your Gravatar registered email address. If you have a registered avatar the blog will display the image beside your comment.

This same method can be used to extend HtmlHelper in many different ways, adding small (or big) utilities that you can code and take advantage from the View in ASP.NET MVC.



There are no comments for this blog entry.