Rendering a Gravatar image with Razor and C# MVC4

I wanted to write a Helper Extension for Razor which rendered a Gravatar image .. see below:

<div class="Author" style="position:relative;">
    <div style="position:absolute; top:10px;">
        @Html.RenderGravatarImage(Model.AuthorEmail, 100)

The code for the Helper Extension

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Security;

namespace GeekZillaMVC3.Helpers
    public static class GeekZillaHtmlHelperExtensions
        /// <summary>
        /// Gets the gravatar image URL.
        /// </summary>
        /// <param name="emailId">The email id.</param>
        /// <param name="imgSize">Size of the img.</param>
        /// <returns></returns>
        public static MvcHtmlString RenderGravatarImage(this HtmlHelper helper, string emailId, int imgSize)
            // Convert emailID to lower-case
            emailId = emailId.ToLower();

            var hash = FormsAuthentication.HashPasswordForStoringInConfigFile(emailId, "MD5").ToLower();

            // build Gravatar Image URL
            var imageUrl = string.Format(@"<img src=""{0}?s={1}&d=mm&r=g"" />", hash, imgSize);

            return new MvcHtmlString(imageUrl);

The web.config entry

You need to register your namespace in the web.config in the Views folder see GeekZillaMVC3.Helpers below:

  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <add namespace="GeekZillaMVC3.Helpers" />
Author Paul Hayman

Paul is the COO of kwiboo ltd and has more than 20 years IT consultancy experience. He has consulted for a number of blue chip companies and has been exposed to the folowing sectors: Utilities, Telecommunications, Insurance, Media, Investment Banking, Leisure, Legal, CRM, Pharmaceuticals, Interactive Gaming, Mobile Communications, Online Services.

Paul is the COO and co-founder of kwiboo ( and is also the creator of GeekZilla.

Add Comment


Your comment has been received and will be shown once it passes moderation.