在ASP.NET 实现页面点击数记录

方法1

建立Default.aspx Web窗体

Default.aspx.cs文件中加入如下代码:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace HitCount

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!this.IsPostBack)

            {

                Session["first"] = null;

            }

            int count = 0;

            Application.Lock();

            Application.Add("count", count);

            if (Session.IsNewSession == true)

            {

                Application["count"] = (int)Application["count"] + 1;

            }

            Application.UnLock();

            Response.Write("The page has been visited: " + Application["count"] + "Times!");

            

        }

    }

}

 

 

方法2

建立counter.ascx 用户自定义控件,在根目录下加入counter.xml,如下

<?xml version="1.0" standalone="yes"?>

<counter>

  <count>

    <hits>0</hits>

  </count>

</counter>

Counter.ascx.cs文件中加入如下代码:

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 HitCount

{

    public partial class counter : System.Web.UI.UserControl

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            if (!this.IsPostBack)

            {

          /*

                  使用Session目的是避免同一用户不同刷新页面使hits增加1

          */

                Session["first"] = DateTime.Now;                      

         this.HitCount();

            }

            DataSet tmpDS = new DataSet();

            tmpDS.ReadXml(HttpContext.Current.Server.MapPath("~/counter.xml"));

            Label1.Text = tmpDS.Tables[0].Rows[0]["hits"].ToString();

           

        }

        private void HitCount()

        {

            DataSet tmpDS = new DataSet();

            tmpDS.ReadXml(HttpContext.Current.Server.MapPath("~/counter.xml"));

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

            if (Session.IsNewSession == true)

            {

                hits += 1;

            }

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

            tmpDS.WriteXml(HttpContext.Current.Server.MapPath("~/counter.xml"));

        }

    }

}

counter.ascx 前台添加一个 Lable控件 ID="Label1"

..

OK, enjoy it.. That is it..

posted @ 2009-12-11 17:31  Mangos  阅读(1000)  评论(0编辑  收藏  举报