问题
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:
- In
App_code
create an abstract class (MyBasePage
for example) which inherits fromPage
class and add abstract property (TestID
in your example), - Create a page which inherits from
MyBasePage
and implement the property, - In
.ascx.cs
castthis.Page
asMyBasePage
and use the property you want.
来源:https://stackoverflow.com/questions/48309613/web-control-access-web-form-methods