ASP.Net Variable Scope

I have a slightly strange problem related to the scope of variables. I declared the variable as follows:

public partial class MyClass: System.Web.UI.Page
{
    protected static int MyGlobalVariable;

    protected void MyFunction()
    {
        MyGlobalVariable = 1;
    }
}

And that works great on my page. However, when two users use the same page, I find that I’m redirecting. If one user set the variable to 5 and the other then, then access to this variable would be 5. How can I set the variable so that it is accessible only to the user who originally set it?

+3
source share
3 answers

MyGlobalVariable , , , , .

int static, , , Viewstate ( ) Session ( )

.

protected int MyGlobalVariable
{
    get
    {
        return ViewState["MyGlobalVariable"] != null ? Convert.ToInt32(ViewState["MyGlobalVariable"] : 0;
    }
    set
    {
        ViewState["MyGlobalVariable"] = value;
    }
}

protected int MyGlobalVariable
{
    get
    {
        return Session["MyGlobalVariable"] != null ? Convert.ToInt32(Session["MyGlobalVariable"] : 0;
    }
    set
    {
        Session["MyGlobalVariable"] = value;
    }
}
+6

:

protected int MyGlobalVariable;

+2

STATIC- .

. , .

Well, if you use this, you need "public" varilables. Then you will need to use some tricks, such as viewstate or session.

0
source

Source: https://habr.com/ru/post/1707406/


All Articles