简体   繁体   中英

Declaring a global variable in ASP.NET codebehind

I want to declare a Dictionary<string, object> variable but don't know where/how to. The values in the dictionary will be objects from the Page (ListBoxes, DropDownLists, etc) so I can't exactly create a helper class somewhere else. Is there any way I can make this variable accessible from each method in the codebehind?

There are three places where you can store data. At the application level, which makes the data accessible to all sessions. The session level, which makes the data available to all pages for that specific user. Or, the page level, which makes it available to the current page, between postbacks. See examples below:

Storing at Application Level
Sample Class to encapsulate storage:

 public static class ApplicationData
{
    private static Dictionary<string, object> _someData = new Dictionary<string, object>();

    public static Dictionary<string, object> SomeData
    {
        get
        {
            return _someData;
        }

    }

}

Usage Sample (in Page Load event): This will increment the value across all sessions. To try it, open two browsers on your machine and it the same URL. Notice how the value is incremented for each user's request.

            // Application Data Usage
        if (ApplicationData.SomeData.ContainsKey("AppKey"))
        {
            ApplicationData.SomeData["AppKey"] = (int)ApplicationData.SomeData["AppKey"] + 1;
        }
        else
        {
            ApplicationData.SomeData["AppKey"] = 1;
        }
        Response.Write("App Data " + (int)ApplicationData.SomeData["AppKey"] + "<br />");

Storing at Session Level: Sample Class to encapsulate storage:

    public class SessionData
{
    private Dictionary<string, object> _someData;

    private SessionData()
    {
        _someData = new Dictionary<string, object>();
    }

    public static Dictionary<string, object> SomeData
    {
        get
        {
            SessionData sessionData = (SessionData)HttpContext.Current.Session["sessionData"];
            if (sessionData == null)
            {
                sessionData = new SessionData();
                HttpContext.Current.Session["sessionData"] = sessionData;
            }
            return sessionData._someData;
        }

    }
}

Usage Sample (in Page Load event): Value is incremented for the current user's session. It will not increment when another session is running on the server.

            // Session Data Usage.
        if (SessionData.SomeData.ContainsKey("SessionKey"))
        {
            SessionData.SomeData["SessionKey"] = (int)SessionData.SomeData["SessionKey"] + 1;
        }
        else
        {
            SessionData.SomeData["SessionKey"] = 1;
        }
        Response.Write("Session Data " + (int)SessionData.SomeData["SessionKey"] + "<br />");

Page Level Storage

Within the page:

    private Dictionary<string, int> _someData;

    private Dictionary<string, int> SomeData
    {
        get
        {
            if (_someData == null)
            {
                _someData = (Dictionary<string, int>)ViewState["someData"];
                if (_someData == null)
                {
                    _someData = new Dictionary<string, int>();
                    ViewState.Add("someData", _someData);
                }   
            }                             
            return _someData;
        }
    }

Sample Usage

in Page Load handler

        if (!this.IsPostBack)
        {
            incrementPageState();
            Response.Write("Page Data " + SomeData["myKey"] + "<br />");    
        }
    private void incrementPageState()
    {
        // Page Data Usage
        if (SomeData.ContainsKey("myKey"))
        {
            SomeData["myKey"] = SomeData["myKey"] + 1;
        }
        else
        {
            SomeData["myKey"] = 1;
        }
    }

on button click:

    protected void hello_Click(object sender, EventArgs e)
    {
        incrementPageState();
        Response.Write("Page Data " + SomeData["myKey"] + "<br />");    

    }

Keep in mind, that the ViewState is not Deserialized on Page Load, however it will be deserialized in event handlers like Button.Click

All code has been tested, if you want the full solution, let me know, I will email it to you.

Declare the variable inside the class, but outside of any method. for Example:

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        private Dictionary<string, object> myDictionary;

        protected void Page_Load(object sender, EventArgs e)
        {
            myDictionary = new Dictionary<string, object>();
            myDictionary.Add("test", "Some Test String as Object");
        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            myDictionary.Add("TextBox1Value", TextBox1.Text);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            TextBox1.Text = myDictionary["test"].ToString();
        }
    }
}

There are multiple options on what kind of data, how long you'd want to store etc. look at Session State , ViewState , Application State

Based on your Global Variable requirement I can think of two possibilities.

  1. Use a static class and a static variable as shown in below code.

     internal static class GlobalData { public static Dictionary<string, object> SomeData { get; set; } } 

Now using it

        //initialize it once in Application_Start or something.
        GlobalData.SomeData = new Dictionary<string, object>();

        //use it wherever you want.
        object o = GlobalData.SomeData["abc"];

2 use Application state to store your global data. as below.

        //Store it in application state
        Application["YourObjectUniqueName"] = new Dictionary<string, object>();

        //access it wherever using
        Application["YourObjectUniqueName"]["abc"] 

You can create one class file that must be public(say general.cs), so that it can be easily accessible. And in that class file you can define this global variable.

You can access this variable from any of the other pages or Class as it is defined public and can utilize this globally variable by creating the instance of the class.

You can declare the variable in the codebehind on the line right after the class declaration line. This will work if you just want to use that on one page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM