Search code examples
asp.net-mvcdatabasepageviews

Count Pageviews in MVC and log in Database


First let me thank everyone who has contributed in my education, it has helped a great deal and I have learned a lot in 7 months.

I have been requested to count every pageview when someone visits a details page. I updated my database to add a pageview column but I am unsure of how to do anything else. I think I should put the code on my details ActionResult on my controller since that is the page I want to be tracked. If this is wrong please correct me.

 public ActionResult Details(int id, int? yearId)
        {
            var dbTest = _testRepository.Id(id);
            var year = yearId == null ? dbTest.LastYear : dbTest.Date.Single(i => i.Id == yearId);
            var vm = new DetailsVM
            {
                Test = _mapper.Map<TestVM>(year)
            };

            return View(vm);
        }

Above is my action result. What it does is collects everything from the database and displays it on a details cshtml page. This code works. How do I get each pageview to count and log into my database using the column name pageview. Please explain your methods so I can learn from it.

Edit:
I have looked into Google Analytics and it isn't what I am looking for. I just want something to use for organization.

I have also included my database model which hopefully provides more information.

public class Test
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public ICollection<TestYear> Years { get; set; }
        [NotMapped]
        public TestYear LastYear {
            get {
                return this.Years.OrderByDescending(i => i.Year).FirstOrDefault();
            }
        }
        public int PageViews { get; set; }
    }

Solution

  • I ended up just making a method in my repository to add a counter to the page-views column in my database every time an id was hit.

    public void AddView(int id)
        {
            var view = _context.Tests.Single(i => i.Id == id);
            view.PageViews++;
            _context.SaveChanges();
        }