Search code examples
asp.netasp.net-mvckentico

Kentico CMS - Register page (Web Analytics) view using MVC Model


I have a fairly small Kentico website that's using the MVC model. I've enabled Web Analytics, but it's not recording page views. I disabled logging using JavaScript in the settings.

It is recording entry and exit pages, and visitors in general, but not specifics about the visitor, like their browser, country etc, or any page views.

I've checked the Process analytics log schedule job, and it's running correctly.

Is there something I need to do?


Solution

  • Web analytics are not tracked on MVC pages natively unlike portal pages. However, some basic statistics are recorded for MVC template based pages (such as exit pages, general visitors, page not founds). To record full set of statistics you have to have 'Log via JavaScript snippet' enabled and put a little bit of code to your page.

    Before all, add a 'using' @using CMS.Helpers;. Then insert the following code to page header:

    <script type="text/javascript" src="@URLHelper.ResolveUrl("~/CMSScripts/WebServiceCall.js")"></script>
    

    The following code prepares values which are gonna be passed as web service call parameters:

    @{
        var page = DocumentContext.CurrentPageInfo;
    
        if (page != null)
        {
            ViewBag.PageGuid = (page.DocumentGUID == Guid.Empty) ? String.Empty : page.DocumentGUID.ToString();
            ViewBag.SiteId = (page.NodeSiteID > 0) ? page.NodeSiteID.ToString() : String.Empty;
        }
    
        ViewBag.Referrer = (Request.UrlReferrer != null) ? Request.UrlReferrer.ToString() : String.Empty;
    }
    

    And finally add the following script at the end of the page (to behave as startup script) to call Kentico web service that logs web analytics:

    <script type="text/javascript">
    WebServiceCall('@URLHelper.ResolveUrl("~/CMSPages/WebAnalyticsService.asmx")', 'LogHits', '{ "parameters": { "pageGUID" : "@ViewBag.PageGuid", "pagesiteId" : "@ViewBag.SiteId", "referrer" : "@ViewBag.Referrer" }}');