MVC HtmlHelper for Google Charts
Asp.net Mvc has an awesome little class called the HtmlHelper class. I have only recently started to get into creating custom HtmlHelpers, and I thought that creating a small Google charting helper would be a good place to start.
From the Microsoft MSDN site:
The HtmlHelper class provides a set of helper methods whose purpose is to help you create HTML controls programmatically. All HtmlHelper methods generate plain HTML and return the result as a string.
This is great if you need to create html that you are constantly reusing. For this example I am using the Google charting API. It allows you to dynamically generate charts and you don't need to download or install anything. There are loads of different charts that you can generate with the API including line charts, bar charts, pie charts and maps to name a few. In order to create a simple chart you need to use the following code:
Which will produce the following:
This is a good example to get started with, so lets get started. First, you need to create a new class, lets call it GoogleChart.
Next lets create the method that will accept some values and return the html we need as a string:
public static class GoogleChart
{
/// <summary>
/// Draws the chart.
/// </summary>
/// <param name="helper">The helper.</param>
/// <param name="chartType">Type of the chart.</param>
/// <param name="chartData">The chart data.</param>
/// <param name="chartSize">Size of the chart.</param>
/// <param name="chartLabel">The chart label.</param>
/// <returns></returns>
public static string DrawChart(this HtmlHelper helper, string chartType, string chartData, string chartSize, string chartLabel)
{
StringBuilder chartHtml = new StringBuilder("<img src='http://chart.apis.google.com/chart?chs=");
chartHtml.Append(chartSize);
chartHtml.Append("&chd=t:");
chartHtml.Append(chartData);
chartHtml.Append("&cht=");
chartHtml.Append(chartType);
chartHtml.Append("&chl=");
chartHtml.Append(chartLabel);
chartHtml.Append("' />");
return chartHtml.ToString();
}
If we need to call this code on our view we simply do the following.
The intellisense now picks up the values we added in our class, and returns the following code on the view:
<IMG src="http://chart.apis.google.com/chart?chs=250x100
&chd=t:40,60,60
&cht=p
&chl=Pie Chart">
And tada....

It's as simple as that and this functionality can be used all over your site. This helper can also be extended to accept different objects, depending on your model, and you may want to consider making this a little more strongly typed. Using the HtmlHelper class can be used in many different circumstances and really just makes life easier.
I've also created a small demo project that can be downloaded here.
Another good example using HtmlHelpers to create a slick little reCaptcha HtmlHelper can be found here.