This project is read-only.

Gravatar Tutorial

This tutorial illustrates the usage of the Gravatar HtmlHelper that can be found in the DigitallyCreated.Utilities.Mvc assembly. The Gravatar extension method can be found in the GravatarHtmlHelpers class. The tutorial expects that you know C# and ASP.NET MVC.

Gravatar is a really nice free web service that allows a user to associate his or her email address with an avatar picture. Then, when that user visits a website that uses gravatars and posts comments etc, the website can display the avatar that Gravatar has stored as associated with his or her email address. The Gravatar HtmlHelper makes this really easy to do in ASP.NET MVC.

Effectively all the HtmlHelper does is output a simply img tag with the URL set to the Gravatar URL. You should read Gravatar's short page on the URL before continuing so you understand the different Gravatar options.

For the following example, assume the Model for the View is strongly typed to this class:

public class User
    public string DisplayName { get; set; }
    public string Email { get; set; }

So, in the view we will use the Gravatar HtmlHelper to show the user's Gravatar (the user being the User object that is the view's model):

<% string gravatarTitle = String.Format("{0}'s Gravatar", Model.DisplayName); %>
<%= Html.Gravatar(Model.Email, GravatarDefaults.Indenticon, 80, GravatarRating.PG, new Dictionary<string, object> { { "alt", gravatarTitle }, {"title", gravatarTitle} })%>

The first parameter passed to the HtmlHelper is the user's email address. The second is what Gravatar default you want to use if the that email doesn't have a Gravatar associated with it. The third is the size that you'd like the image to be (height and width; the image is square). The fourth is the rating to use (this uses PG, so we don't get porno avatars!). The fifth is a dictionary of extra attributes we want to set on the img tag. In this case we're setting the alt and title attributes.
There are shorter overloads that you can use if you don't need all those different options. See the code's XMLdoc.

The above example will emit the following HTML (obviously the alt, title and src would be different depending on the user):

<img width="80" height="80" title="Splinkifater's Gravatar" alt="Splinkifater's Gravatar"
     src=";s=80&amp;r=pg" />

Last edited Mar 23, 2010 at 7:18 AM by dchambers, version 2


No comments yet.