3

I have the feeling that i'm missing something key here.

I've tried following guides on http://msdn.microsoft.com/en-us/magazine/cc300437.aspx and on google, but i can't see what i haven't done.

I have some very basic code which i have written just trying to get this to work:

The Default.aspx code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableSessionState="True" %>

<!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>Demo Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="myLabel" runat="server" Text="foo"></asp:Label>
        <asp:LinkButton ID="lnkClickButton" runat="server" OnClick="lnkClickButton_Click" CommandName="Clicky">Click Me</asp:LinkButton>
    </div>
    </form>
</body>
</html>

The Default.aspx.cs code:

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["clickcount"] = 0;
        Cache["clickscount"] = 0;
    }
    protected void lnkClickButton_Click(object sender, EventArgs e)
    {
        Session["clickcount"] = (int)Session["clickcount"] + 1;
        Cache["clickscount"] = (int)Cache["clickscount"] + 1;

        Label myLabel = ((Label)this.FindControl("myLabel"));
        if (myLabel != null)
        {
            myLabel.Text = "Session: " + Session["clickcount"] + "; Cache: " + Cache["clickscount"] + ";";
        }
    }
}

I've tried using both the session object and the cache object to increment the values, but to no avail. I just get 1 every time.

N.B. this is my first asp.net project, also i'm fairly new to c#.

1
  • So many useful points from you all. I want to accept more than one answer, unfortunately i can't Commented May 28, 2012 at 10:26

4 Answers 4

6

Page_Load is ran every postback as well as the initial load. You need to specify no postback in your Page_Load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack){
       Session["clickcount"] = 0;
       Cache["clickscount"] = 0;
    }
}

Better still, specify that it should only be set if it doesn't already have a value:

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["clickcount"] == null){
       Session["clickcount"] = 0;
    }
}

Just to clarify, the reason that it is better to only set the value if it isn't already set is that Page.IsPostBack is false every time someone directly visits the page. Say for instance you have your page http://example.com/Demo/Default.aspx and at the top you have a logo which you wrap in logo here, the session would be reset every time somebody clicked on the logo, even though they didn't actually leave the page. Also happens if they refresh on their browser without re-posting the last post.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, knew i was being silly somewhere. I had kinda assumed that was a constructor and was run once. Silly Me - I'll accept your answer when it lets me cos its got the most detail
I've edited your answer for anyone else looking for this. Hopefully it will be helpful
4

Read on MSDN : Page.IsPostBack Property - Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.

vlue of property is true if the page is being loaded in response to a client postback; otherwise, false.

code like this ...you need to put the code in !IsPostBack as like below

protected void Page_Load(object sender, EventArgs e)     
{
     if(!IsPostBack)
    {
         Session["clickcount"] = 0;
         Cache["clickscount"] = 0;
    }
 } 

serverside control generate postback to page it self so the code that you dont wnat to execute on each postbck need to be put as above

this will resolve your issue easily...

further to this you can create static property for count like this

Check my post on : Programming Practice for Server Side State Maintenance Variable

private int ClickCount
{
  get 
   {
     if (Session["clickcount"] == null)
     {         Session["clickcount"] = 0; return 0;      }
     else 
        return (int)Session["clickcount"] ; 
   }
   set
   {
      Session["clickcount"] = value;
   }
} 

than in final code

protected void Page_Load(object sender, EventArgs e)     
{
         if(!IsPostBack)
        {
            ClickCount = 0; 
        }
}

protected void lnkClickButton_Click(object sender, EventArgs e)
{
              int val = ClickCount ;
              ClickCount  = val + 1; 
}

3 Comments

Just tried the static property, you can't access session from within a static property, but if you make it non static it works. Edited your post to reflect this
@MMM - its working fine check my post ... pranayamr.blogspot.com/2011/01/…
Hi Pranay, your post doesn't use the static keyword either.
1

Writing:

Session["clickcount"] = 0;

In the Page_Load will cause the counter to be reset every time the user enters the page.

Seems to me you want something like this:

protected void lnkClickButton_Click(object sender, EventArgs e)
{
    if (Session["clickcount"] == null)
    {
            Session["clickcount"] = 1;
    }
    else
    {
           Session["clickscount"] = (int)Session["clickscount"] + 1;
    }

    Label myLabel = ((Label)this.FindControl("myLabel"));
    if (myLabel != null)
    {
        myLabel.Text = "Session: " + Session["clickcount"] + "; 
    }
}

Comments

1

You get 1 because every post back your session and cache variable equal to 0.

protected void Page_Load(object sender, EventArgs e)
{
    Session["clickcount"] = 0;
    Cache["clickscount"] = 0;
}

And button click occur after the page_load, So you should use IsPostback property.

 protected void Page_Load(object sender, EventArgs e)     

{

 if(!IsPostBack)
{
     Session["clickcount"] = 0;
     Cache["clickscount"] = 0;
}

}

Now these variables initialize only when page is loaded.

You should go through following link. It is described Asp.net page life.

http://msdn.microsoft.com/en-us/library/ms178472.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.