问题
I have a web page and it contains an user control inside of it. I have a property on the aspx page which gets set in the pageinit method and I need to that propery on ascx page. How can I get it?
回答1:
Create a public property inside the ascx and set it at the same time you set in the aspx page.
Just to let you know, PreInit is a EventHandler not a method.
回答2:
MyAdminPage myPageInstance = this.Parent as MyAdminPage;
if(myPageInstance != null)
{
...
}
There has been a few questions on this.
Reference .aspx property from .ascx
回答3:
The easiest options are as follows:
- Use a public variable and access it from the parent page.
- Assign the variable to a hidden field on the ascx front end. A field like this:
<asp:HiddenField ID="ascxField" runat="server" />
.
The example below is for #1, but #2 is almost the same.
Example #1:
Aspx page:
Front end:
<%@ Register TagPrefix="Admin" TagName="MyUserControl" Src="~/UserControls/.../MyUserControl" %>
...
<Admin:MyUserControl ID="MyUserControl" AutoPostBack="true" runat="server" Visible ="false" />
Code Behind:
this.MyUserControl.Variable1 = 1;
this.MyUserControl.Variable2= "value";
Ascx page:
Code Behind
public int Variable1 { get; set; }
public string Variable2 { get; set; }
来源:https://stackoverflow.com/questions/10657491/pass-a-value-from-aspx-to-ascx