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

发布于 2024-10-24 16:46:46 字数 167 浏览 16 评论 0原文

我想声明一个 Dictionary 变量,但不知道在哪里/如何声明。字典中的值将是页面中的对象(ListBoxes、DropDownLists 等),因此我无法在其他地方准确创建辅助类。有什么方法可以让代码隐藏中的每个方法访问此变量吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

黑凤梨 2024-10-31 16:46:46

您可以在三个位置存储数据。在应用程序级别,这使得所有会话都可以访问数据。会话级别,使数据可供该特定用户的所有页面使用。或者,页面级别,使其在回发之间可用于当前页面。请参阅下面的示例:

在应用程序级别存储
封装存储的示例类:

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

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

    }

}

用法示例(在页面加载事件中):
这将增加所有会话的值。要尝试它,请在您的计算机上打开两个浏览器并使用相同的 URL。请注意该值如何针对每个用户的请求递增。

            // 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 />");

在会话级别存储:
封装存储的示例类:

    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;
        }

    }
}

用法示例(在页面加载事件中):
当前用户会话的值会增加。当服务器上运行另一个会话时,它不会增加。

            // 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 />");

页面级存储

页面内:

    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;
        }
    }

示例用法

页面加载处理程序中的

        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;
        }
    }

单击按钮时

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

    }

:请记住,ViewState 在页面加载时不会反序列化,但它将在 Button.Click 等事件处理程序中反序列化

所有代码均已测试,如果您想要完整的解决方案,请告诉我,我会通过电子邮件发送给您。

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.

最美不过初阳 2024-10-31 16:46:46

在类内部但在任何方法外部声明变量。例如:

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();
        }
    }
}

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();
        }
    }
}
听风吹 2024-10-31 16:46:46

关于数据类型、要存储多长时间等有多种选项。请查看 会话状态视图状态应用程序状态

基于您的全局变量要求我能想到两种可能性。

  1. 使用静态类和静态变量,如下面的代码所示。

    内部静态类GlobalData
    {
        公共静态字典<字符串,对象>一些数据{获取;放; }
    }
    

现在使用它

        //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 使用 Application 状态来存储您的全局数据。如下。

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

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

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"] 
怀念你的温柔 2024-10-31 16:46:46

您可以创建一个必须是公共的类文件(例如general.cs),以便可以轻松访问它。在该类文件中,您可以定义这个全局变量。

您可以从任何其他页面或类访问此变量,因为它是公共定义的,并且可以通过创建类的实例来使用此全局变量。

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.

咋地 2024-10-31 16:46:46

您可以在类声明行之后的代码隐藏行中声明变量。如果您只想在一页上使用它,这将起作用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文