public static class Google
{
public static IHtmlString GetAnalyticsHtml(string id = null)
{
var accountId = id;
if (string.IsNullOrWhiteSpace(accountId))
accountId = ConfigurationManager.AppSettings["GoogleAnalyticAccount"];
if (string.IsNullOrWhiteSpace(accountId))
throw new ApplicationException("You must specify a Google Account Id, you can for example use appSettings with the key 'GoogleAnalyticAccount' in web.config or pass the id as an argument");
return
new HtmlString(@"
<script type=""text/javascript"">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', '" + accountId + @"']);
_gaq.push(['_trackPageview']);
(function () {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>");
}
}
Just add the following to a page using Razor:
@Google.GetAnalyticsHtml()
WebMatrix have several helper methods for this, but they aren't part of the ASP.Net MVC 3.0 and the Razor view engine, so I created one.
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


1.28k
0




Mark 'aspmvc' tag as 'like'
Mark 'aspmvc' tag as 'ignore'