【问题标题】:Access TextBox value of an ASP.NET page from C# class从 C# 类访问 ASP.NET 页面的 TextBox 值
【发布时间】:2013-03-16 13:58:39
【问题描述】:

假设 ASP.NET 页面上有一个 TextBox

<asp:TextBox id="DateTextBox" runat="server" />

在代码隐藏中设置了一些值。

如何通过 HttpContext 或任何其他方式从另一类 C# 代码文件中访问该值?

【问题讨论】:

  • 你必须把它推到那个班级。
  • 会话是通过另一个类访问值的最佳方式。
  • Sessions 对于我的简单任务来说似乎是非常繁重的解决方案。
  • 我会重新考虑你的设计。

标签: asp.net httpcontext


【解决方案1】:

您甚至可以通过静态方法通过HttpContext 访问页面中的属性。

在您的页面中:

public string DateTextBoxText
{
    get{ return this.DateTextBox.Text; }
    set{ this.DateTextBox.Text = value; }
}

其他地方(即使在不同的 dll 中):

public class Data
{
   public static string GetData() 
   { 
       TypeOfYourPage page = HttpContext.Current.Handler as TypeOfYourPage;
       if (page != null)
       {
          return page.DateTextBoxText;
          //btw, what a strange method!
       }
       return null;
    }
}

请注意,这只有在此页面的生命周期内调用时才有效。

通常最好使用ViewState 或Session 在回发期间维护变量。或者当你有这个页面的引用时直接使用上面的属性。

【讨论】:

  • 默认 VS 生成的 .aspx 的 TypeOfYourPage 是什么?我应该在这里放什么?
  • @sublay: 您的页面类型 ;-) 只需查看继承自 Page 的类的名称(例如,在代码隐藏或 aspx 上的页面指令中)标记)。
【解决方案2】:

您可以在控件中创建一个public property,以返回对文本框的引用。

然后您可以使用此属性来引用文本框。

或

您可以存储到session,然后在整个应用程序中访问它。

【讨论】:

  • 有 'protected global::System.Web.UI.WebControls.TextBox DateTextBox;'在 myfile.aspx.designer.cs 我应该在这里更改为 public 吗?
【解决方案3】:

存储在HttpContext Sessionhttp://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net

//Storing UserName in Session
Session["DateTextBox"] = DateTextBox.Text;

现在,让我们看看如何从会话中检索值:

//Check weather session variable null or not
if (Session["DateTextBox"] != null)
{
 // use it...
}

【讨论】:

    【解决方案4】:

    您可以在回发期间将值放入 Session 中。然后从另一个类中的 Session 访问它。所以在你的表单加载事件中写下这个:

    Session["MyValue"] = DateTextBox.Text
    

    然后在另一个班级写下:

    var val = HttpContext.Current.Session["MyValue"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      相关资源
      最近更新 更多