2

How can I put variables that have scope the whole session on ASP.NET Page (I mean in the class that stands behind the aspx page)? Is the only way to put the variable in the Session object?

For example:

public partial class Test_ : System.Web.UI.Page
{
    private int idx = 0;

    protected void Button1_Click(object sender, EventArgs e)
    {
        Button1.Text = (idx++).ToString();
    }
}

I want on every click on this button my index to go up. How can I do this without using the Session object?

2
  • Is there some reason you're against the Session object? From my perspective, this is a session variable, so that's where it belongs. Commented Jan 12, 2010 at 21:24
  • Too much reliance on session can cause performance issues with the server. +1 for Marek's answer, viewstate is the most correct choice, given that this is local to the page and its postbacks. Commented Jan 12, 2010 at 21:27

3 Answers 3

3

You can put it in ViewState instead

public partial class Test_ : System.Web.UI.Page {

    protected void Button1_Click(object sender, EventArgs e) {
        if(ViewState["idx"] == null) {
            ViewState["idx"] = 0;
        }
        int idx = Convert.ToInt32(ViewState["idx"]);

        Button1.Text = (idx++).ToString();

        ViewState["idx"] = idx;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

10x! that gave me some light upon the problem ;) Still I'm gonna go deeper in the article seth proposed.
Definitely a good read - obviously there are plenty of ways to accomplish this.
2

ViewState seems to be what you're looking for here, so long as that counter doesn't need to be maintained outside the scope of this page. Keep in mind that a page refresh will reset the counter though. Also, if the counter is sensitive information, be wary that it will be stored (encrypted) in the rendered HTML whereas Session values are stored server-side.

Comments

1

There are a number of options besides the session. Take a look at Nine Options for Managing Persistent User State in Your ASP.NET Application.

For this sort of data, you probably would want use the session store.

1 Comment

Session state is a poor choice for data like this, since it potentially has to be written to and read from a database for each request, and for every page on the site, instead of just the page that needs it.

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.