john
john

Reputation: 834

How to get the number of views for a page in ASP NET MVC 5

Im not asking for outside tools and plugins for this, i just need a simple solution to do this using asp.net.

Thanks in advance for any help.

Upvotes: 3

Views: 3934

Answers (2)

Haitham Shaddad
Haitham Shaddad

Reputation: 4456

You need something that runs for every request, you can use an action filter and in the ActionExecuted method, get the request URL and increament the number of this URL.

You will have to have a table with the URL and PageViews initlaized to zero, on each request increment this PageViews variable.

Edit: Sample code below

  1. Create a folder under your web project called Filters
  2. Create a new class under this folder and name it PageVisitCountFilter, make it inherit from ActionFilterAttribute
  3. Create a class under the Models folder to have the page visits data

    public class PageVisit { public string PageUrl { get; set; } public int Visits { get; set; } }

  4. Add the following code to the ActionFilterAttribute class

    public class PageVisitCountFilter:ActionFilterAttribute
    {
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
    
        PageVisit page = new PageVisit();
        var repository = new PageVisitRepository();
        var pageUrl = filterContext.HttpContext.Request.Url;
    
        var page = repository.GetPageByUrl(pageUrl);
        if(page == null)
        {
            page = new PageVisit { PageUrl = pageUrl, Visits = 1 };
            repository.Save(page);
        }
        else
        {
            page.Visits++;
            repository.Update(page);
        }
    }
    }
    

The repository class is a class that add, updates and retrieves objects of type PageVisit

This way, you will have a table in the database with each page URL and its page visits

Upvotes: 3

Dmitriy Kovalenko
Dmitriy Kovalenko

Reputation: 3616

OK, if you need to get only unique views you can add a cookie, something like Unique_User_Guid and check in js if there are no cookie to send request by ajax, and in action - iterate and save current views count value.

If you need to check for all views, not unique - you can simply add simple codeto your action method, which will get current views value from db, iterate and save.

Upvotes: 0

Related Questions