web控件访问web表单方法

web control access web form methods

我的网络表单包含一个网络控件和一个 asp:HiddenField。我正在尝试访问我的 asxc.cs 文件中的那个隐藏字段。我在我的 aspx.cs 文件中定义了一个 public get,set 块。在 Web 控件中,当我尝试调用 ReportPage.TestID 时,它无法识别报告页面 class。在 webcontrol 中访问 HiddenField 是正确的方法吗?如果是这样,我应该如何访问 ReportPage class?

public partial class ReportPage : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public int TestID
    {
        get
        {
            return Convert.ToInt32(TestIDHiddenField.Value);
        }
        set
        {
            TestIDHiddenField.Value = TestID.ToString();
        }
    }
}

由于 Web Site compilation model,您无法从用户控件直接访问页面控件。简而言之,ASP.NET 首先编译 App_code(它的 classes 在所有网站上都是可见的)然后是用户控件(.ascx),当 .aspx 页面使用控制。

解决方法如下所示:

  1. App_code中创建一个摘要class(例如MyBasePage)继承自Pageclass并添加摘要属性( TestID 在你的例子中),
  2. 创建一个继承自MyBasePage的页面并实现属性,
  3. .ascx.cs 中将 this.Page 转换为 MyBasePage 并使用您想要的 属性。