MVC HtmlHelper for Gravatar

Based on a great suggestion from Ben Scheirman and Simone Chiaretta I have converted the Gravatar URL helper class into a HtmlHelper extension method. This was my first stab at making a HtmlHelper extension but it seems to be working nicely and helps me keep my code a lot cleaner. Instead saving the URL (which I would highly advise against) or doing some weird method calling acrobatics in the Controller, I can simply say <%= Html.Gravatar("email@email.com") %> inside the view.

I've added a couple different method definitions for various parameters. You can pass in just an e-mail address, an e-mail and gravatar parameters (see here for more info on gravatar parameters) or an e-mail address, gravatar parameters and html attributes. A quick usage summary is listed below (I'm using my brother Joel's gravatar in the examples)

<%= Html.Gravatar("email@email.com") %>

Base Gravatar Helper 

 

<%= Html.Gravatar("email@email.com", new  { s = "128", r = "pg" })%>

Gravatar helper with optional Gravatar Parameters

 


<%= Html.Gravatar("email@email.com", null, new  { style = "border:5px solid" })%>  

Helper with HTML attributes. Please note, this is still expecting the Gravatar parameters — you can pass in null if you want to just grab the default image with no additional properties.

 


<%= Html.Gravatar("email@email.com", new { s = "128", r = "pg" }, new { style="border:5px solid;"})%>

Helper with both Gravatar parameters and HTML attributes

 

Anyways, I've posted the class file below. Hopefully you find it useful — I would love to hear what your thoughts are or of any changes you would like to see.
GravatarHelper.cs (2.72 kb)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>