简体   繁体   English

在ASP.NET代码中声明全局变量

[英]Declaring a global variable in ASP.NET codebehind

I want to declare a Dictionary<string, object> variable but don't know where/how to. 我想声明一个Dictionary<string, object>变量,但是不知道在哪里/如何去做。 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. 字典中的值将是Page中的对象(ListBoxes,DropDownLists等),因此我无法在其他地方完全创建帮助器类。 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. 要尝试,请在您的计算机上打开两个浏览器,并且使用相同的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 请记住,ViewState不会在页面加载时反序列化,但是会在事件处理程序(如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 关于什么类型的数据,要存储多长时间等有多种选择。查看会话状态ViewState应用程序状态

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. 2使用Application状态存储您的全局数据。 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. 您可以创建一个必须是公共的类文件(例如general.cs),以便可以轻松访问它。 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. 如果您只想在一页上使用它,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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