Filled Under:

How To Store Page Hit Count In ASP.NET

Share

Hello I am Tapan Kumar



 In ASPX Page....


While developing a static website, where no database is used then you might need to add a functionality of page hit count in your website. Its very easy and simple to achieve this functionality using a xml file. we can dynamically update the xml file data and can show this to your users.



Here I am showing you some of my codes I have done for achieving this functionality in a static website.



Add the following code in your .aspx page, where you want the hit count to appear. Just add the label there with an id.





<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" 
Inherits="Send_SMS.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblCounter" runat="server"></asp:Label>
</div>
</form>
</body>
</html>





      Now add a xml file named "counter.xml " to the root folder of your project. Here is how your xml file will look like.





<?xml version="1.0" standalone="yes"?>
<counter>
<count>
<hits>0</hits>
</count>
</counter>


In Code Behind Page ....




Just add the bellow written codes into the .cs file of the aspx page you have added. Here we are storing the hit count in a XML file and update the data of the XML file dynamically.





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace Send_SMS
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.countMe();

DataSet tmpDs = new DataSet();

tmpDs.ReadXml("C:/Users/tapank/Documents/Send SMS/counter.xml");

lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}

private void countMe()
{
DataSet tmpDs = new DataSet();

tmpDs.ReadXml("C:/Users/tapank/Documents/Send SMS/counter.xml");

int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());

hits += 1;

tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();

tmpDs.WriteXml("C:/Users/tapank/Documents/Send SMS/counter.xml");

}
}
}



Basically what we did in this article is something like, we are storing the hit count of a page in a xml file and updating that data dynamically. This is very helpful if you are not using any database in your website basically for static websites.



Happy coding.....