Thursday, March 22, 2012

Strongly Type Web Forms

How does a User Control invoke a method on its parent page? Say I have a publicMethod in code behind for an aspx page:
...
public void SomeImportantMethod() { /* do important stuff */}
...
From an Event Handler within the User Control, I'd like to invoke a method on the page in which the User Control is embedded. If I stop in the debugger and inspect this.Page, I see that it has a type of "ASP.MyAspxPage"... where did that come from? Can I delcare it intentionally somewhere?
TIA,
Geo
Your MyAspxPage is your custom page class, which inherits from the System.Web.UI.Page class.
The thing with UserControls is though, that you don't know what parent page they could be in at run-time.
So, to be safe, if you want to call a particular method on the parentPage, I'd say let your Page implement your interface which contains themethod signature (and other stuff if you want).
In your UserControl you then do a defensive cast (using the as keyword)to that interface and check for != null. You then simply call yourmethod on your interface object.
Hope that helps.
Wim

Yes, that does help. It helped in that I was hung up in anold paradigm and should get over it and just use an interface. So, thanks, that helped me get the job done.
I guess I was stuck in theOLD ASP.NET 1.1 code behind days where an ASPX page would have a code behind page which had a namespace declaration and the web form would be a public class derived from System.Web.UI.Page. So, from any C# code I could say:
MyNamespace.MyPage myPage = this.Page as MyNameSpace.MyPage;
if ( myPage != null)
{
myPage.MyMethod("hello world");
}
else
{
Response.Write("what gives?");
}
No fuss no muss, no interfaces.
I think I better go find an article or 2 on code beside or what ever it is we call it now.
Thanks again,
geo

Hello.

I think that you can also use the @.reference directive to introduce the type of the page in the user control (haven't tried it though).

0 comments:

Post a Comment