【问题标题】:Instantiating class so public properties are available for all event handlers in page?实例化类以便公共属性可用于页面中的所有事件处理程序?
【发布时间】:2014-09-04 21:24:24
【问题描述】:

如果不使用 Session 变量或静态类,是否可以在一个 Web 表单中实例化可供所有事件处理程序使用的类?

例如,我的代码如下所示。我实例化 Car 并在 Page_Load 中设置 property 颜色。我知道我无法从另一个事件处理程序访问它。

我不喜欢使用会话变量,因为它们往往会过期,而且这里的用户往往会转到一个页面,然后将其打开一段时间。我总是可以设置会话的超时,但我更喜欢在整个页面的生命周期中持续的东西。

namespace MyNamespace
{
    public partial class ToErase : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Car myCar = new Car();
            myCar.Color = "Black";
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            //Have access to myCar.Color here;
            //Response.Write(myCar.Color);
        }
    }
    public class Car
    {
        public string Color { get; set; }
    }
}

【问题讨论】:

    标签: c# asp.net .net


    【解决方案1】:

    如果您的问题是关于持久性,那么在 WebForms 中,ViewState 会浮现在脑海中(如上所述)。

    根据用例,在一天结束时,您可以更多地涉及客户端,使用基于客户端的持久性(例如 DOM 存储等)。在一天结束时,像click 这样的事件 发生在客户端...ASP.Net 为您抽象了其中的大部分内容。如果您检查了 WebForms 页面的来源,您会看到所有为您“魔法”的 Javascript。

    第...

    【讨论】:

    • 在持久化方面,类实例和视图状态会有区别吗?
    【解决方案2】:

    您可以如下定义它,然后您就可以访问它:-

     public partial class ToErase : System.Web.UI.Page
        {
            private Car myCar;
    
            protected void Page_Load(object sender, EventArgs e)
            {
                this.myCar = new Car();
                this.myCar.Color = "Black";
            }
    
            protected void Button1_Click(object sender, EventArgs e)
            {
                this.myCar.Color = "Blue"; ////You can access it here
                //Have access to myCar.Color here;
                Response.Write(this.myCar.Color);
            }
        }
        public class Car
        {
            public string Color { get; set; }
        }
    

    【讨论】:

      【解决方案3】:

      我错过了什么吗?只需要

      public partial class ToErase : System.Web.UI.Page
      {
          private Car myCar;
          protected void Page_Load(object sender, EventArgs e)
          {....}
      
      }
      

      【讨论】:

        猜你喜欢
        • 2011-04-05
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多