4
votes

Using .NET MVC 3, I'd like to display page views on each page of my site. I have google analytics set up.

I'm aware there is an API, but have no idea where to start.

Any pointers for what I need, and more specifically what to be looking at for displaying page views?

1

1 Answers

5
votes

Create a file in your Views/Shared folder called _GoogleAnalytics.cshtml (using the underscore in the front is a method of indicating a partial view. It has no effect in MVC, it's just a practice I see done a lot in demo's and screen casts.

Put your google analytics code in it. (make sure to put in your own identifier from Google)

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-########-1']);
  _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>

Then in your _Layout.cshtml page add this line (assuming you are using Razor)

@Html.RenderPartial("_GoogleAnalytics")

Edit: Just re-read the question, It just occurred to me what you may be looking for is a means to display just the hit counter using data pulled from Google Analytics API?

Which if that's the case I think I missed that part. I've not done this myself but this may be a good start? http://code.google.com/apis/analytics/docs/mgmt/mgmtFeedReference.html#profileFeed