google analytics in my MVC file layout page

I am trying to use google analytics in my MVC file layout page

The existing code functionality is based on a web form. There is a tag to an ascx file called google analytics.ascx in the web form.

The google analytics code would display the full javascript to track open web pages and links .

 

The existing google analytics ascx layout file consists of following code:

<script>

   var dataLayer = window.dataLayer = window.dataLayer || [];

   dataLayer.push({ 'userId': <%=UserID%>});

</script>

<asp:Literal ID="GoolgeAnalyticsTracking" runat="server" />

 

 

We are now tasked to move to MVC pages and there is no way to reference my existing .ascx file from MVC layout file.

My initial thought is to recreate a google analytics tag using partial view and passing a simple model to that view with userID.

Do you think this is good solution or do you suggest a better approach using sitecore, especially when my MVC skills within Sitecore are limited.

 

Best Wishes

Jane

2 Replies

  • Using a partial view is fine for something fairly lightweight like this. If you wanted to do something "more Sitecore" you could have your partial view in Sitecore rendering and add it to the page via a placeholder, or inject the rendering direct using something like

    @Html.Sitecore().Rendering("/sitecore/layout/Renderings/Sample/Test Rendering", new { Parameters = "UserID=123" })

    Then in the "Test Rendering" you can get the UserID using

    Sitecore.Mvc.Presentation.RenderingContext.Current.Rendering.Parameters["UserID"]
  • Please use MVC partial view and keep it in Head section of yours layout page. It is recommended practice. 

    More Info- https://www.teamscs.com/2014/04/using-google-analytics-asp-net-mvc-website/