MVC HtmlHelper for Google Charts 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.

Santa's little HTML helper

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:

Sample chart

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='");

 chartHtml.Append("' />");
 return chartHtml.ToString();


If we need to call this code on our view we simply do the following.

Google Chart - MVC Helper

The intellisense now picks up the values we added in our class, and returns the following code on the view:

<IMG src="  
&amp;chl=Pie Chart">

And tada....

![Google Chart produced by ASP.NET MVC helper](,60,60&cht=p&chl=Pie Chart)

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.