Mohamad Kiani
Mohamad Kiani

Reputation: 15

Count visitor of one page in asp.net

I have a page that contains a record of a database. I want to count number of visits of that page . I use codes below to counts number of visits of page by increment view field of record. but this increment view randomly. for example when I refresh page the view increment 20 !. my codes for this page is:

 protected void Page_Load(object sender, EventArgs e)
    {
        da db = new da();
        string str = "select views from newstxt where id=" + Request.Params["id"].ToString();
        DataTable dt = new DataTable();
        dt = db.select(str);
        int view = Int32.Parse(dt.Rows[0][0].ToString());
        //increment
        view++;
        //
        str = "update newstxt set views=N'{0}' where id=" + Request.Params["id"].ToString();
        str = string.Format(str, view);
        db.docom(str);


    }

Upvotes: 0

Views: 1625

Answers (3)

Dinesh Rabara
Dinesh Rabara

Reputation: 1127

        Protected Sub Page_Load(sender As Object, e As EventArgs)
            Me.countMe()

            Dim tmpDs As New DataSet()
            tmpDs.ReadXml(Server.MapPath("~/counter.xml"))

            lblCounter.Text = tmpDs.Tables(0).Rows(0)("hits").ToString()
        End Sub

        Private Sub countMe()
            Dim tmpDs As New DataSet()
            tmpDs.ReadXml(Server.MapPath("~/counter.xml"))

            Dim hits As Integer = Int32.Parse(tmpDs.Tables(0).Rows(0)("hits").ToString())

            hits += 1

            tmpDs.Tables(0).Rows(0)("hits") = hits.ToString()

            tmpDs.WriteXml(Server.MapPath("~/counter.xml"))
        End Sub
XML
<?xml version="1.0" encoding="utf-8" ?>
<counter>
  <count>
     <hits>0</hits>
  </count>

Upvotes: 1

Madhu Beela
Madhu Beela

Reputation: 2215

There are couple of ways for this approach simple approach would be using a view state

declare a Property like

 public int ViewCount
    {
        get { return (int)ViewState["viewcount"]; }
        set { ViewState["viewcount"] = value; }
    }

use like ViewCount++; on page load and to get value int value = ViewCount

i hope this helps !!!

Upvotes: 1

Waqas
Waqas

Reputation: 6812

Nothing seems to be wrong with your code but it seems like there is something wrong your Request.Params. Are you using query string, if it is then i would suggest you to use Request.QueryString instead. Also, what you want only if to update the count then you can avoid select query and reduce your code to:

da db = new da();
String str = "UPDATE newstxt SET views = views + 1 WHERE id=" + Request.QueryString["id"].Trim();
db.docom(str);

Upvotes: 0

Related Questions