大家。我一直试图完全按照教科书上的内容进行操作,但无济于事。现在,我的问题是我目前正在尝试创建一个页面计数器来跟踪每个页面被访问了多少次,然后在新页面上显示每个值。
这是所有页面都相同的 C# 计数器代码:
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountMain"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountMain"]);
sessionCount++;
}
protected void Page_PreRender(object sender, EventArgs e)
{
Session["CountMain"] = sessionCount;
}
预渲染是我在网上研究后添加的,在教科书中。没运气。
这是计数器页面 C# 代码:
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
string sessionMain = Session["CountMain"].ToString();
string sessionComment = Session["CountComment"].ToString();
string sessionCompleted = Session["CountCompleted"].ToString();
string sessionCurrent = Session["CountCurrent"].ToString();
string sessionAbout = Session["CountAbout"].ToString();
string sessionContact = Session["CountContact"].ToString();
string sessionCounter = Session["CountCounter"].ToString();
if (Session["CountCounter"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
lblAboutCount.Text = sessionAbout;
lblCommentCount.Text = sessionComment;
lblCompletedCount.Text = sessionCompleted;
lblContactCount.Text = sessionContact;
lblCounterCount.Text = sessionCounter;
lblCurrentCount.Text = sessionCurrent;
lblMainCount.Text = sessionMain;
}
当我尝试运行它时,我得到一个“NullReferenceException 未被用户代码处理,对象引用未设置为对象的实例”。错误。
提前致谢。
编辑#1
好的,感谢 Hexxangonal,计数器现在可以正常工作了。但是,我的计数器页面现在自计数了 2 次。(每次加载时增加 2)
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountCounter"] == null)
{
sessionCount = 0;
Session["CountCounter"] = sessionCount;
}
else
{
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
Session["CountCounter"] = sessionCount;
}
Session["CountCounter"] = sessionCount;
lblAboutCount.Text = Convert.ToString(Session["CountAbout"]);
lblCommentCount.Text = Convert.ToString(Session["CountComment"]);
lblCompletedCount.Text = Convert.ToString(Session["CountCompleted"]);
lblContactCount.Text = Convert.ToString(Session["CountContact"]);
lblCounterCount.Text = Convert.ToString(Session["CountCounter"]);
lblCurrentCount.Text = Convert.ToString(Session["CountCurrent"]);
lblMainCount.Text = Convert.ToString(Session["CountMain"]);
}