web control access web form methods

谁说胖子不能爱 提交于 2019-12-11 14:11:24

问题


My web form contains a web control and a asp:HiddenField. I am trying to access that hiddenfield in my asxc.cs file. I defined a public get,set block in my aspx.cs file. In web control, when I tried to call ReportPage.TestID, it does not recognize the Reportpage class. Is it the right way to access the HiddenField in the webcontrol? If so, how should I access the 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();
        }
    }
}

回答1:


You cannot directly access page controls from a user control because of Web Site compilation model. In short, ASP.NET compiles first App_code (its classes are visible from all the site) then user controls (.ascx) and when .aspx pages which use that controls.

A workaround looks like this:

  1. In App_code create an abstract class (MyBasePage for example) which inherits from Page class and add abstract property (TestID in your example),
  2. Create a page which inherits from MyBasePage and implement the property,
  3. In .ascx.cs cast this.Page as MyBasePage and use the property you want.


来源:https://stackoverflow.com/questions/48309613/web-control-access-web-form-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!