Contract between ASPX and ASCX

Contract between ASPX and ASCX

In the last versions of ASP.NET where not exist the compilation equals ASP.NET 2.0, easily we can invoke an ASPX method inside an User Control (ASCX), casting Page property to a Page type that would be a container but, this can cause a problem when an ASPX not provides a respective method.

With a new compilation in ASP.NET 2.0, it's dificult casting to a Page type because the name is resolved in compilation-time, so, in design-time we don't know this type. If you aren't using the Web Application Project (WAP) and want invoke a Page's method, you will need to create a contract through Interface. This Interface should be only implemented in ASPX where you want the User Control invoke a method. Below is an example:

public interface IConnection
{
    void ExecuteProcedure();
}

public partial class _Default : System.Web.UI.Page, IConnection
public partial class Default2 : System.Web.UI.Page

[ ASCX ]
IConnection connection = this.Page as IConnection;
if (connection != null)
    connection.ExecuteProcedure();
else
    Response.Write("The Page container isn't a IConnection type!");

How you can note, the Default.aspx Page implements a Interface IConnection and Default2.aspx doesn't. Finally, inside an User Control, casting the Page Property to IConnection through as operator that, if isn't a compatible type, it will return null. If you have been using Visual Basic 2005, use the TryCast operator instead.

Comments

# re: Contract between ASPX and ASCX

Friday, January 05, 2007 9:44 PM by Christophe Fouquet

Another solution is to make a base class in AppCode and make a virtual method. You can then use this as a base for your page and override the method. The ascx has then no problem calling via the base. As a side note,

I found that making a base class in AppCode for all pages in a site is really handy. For instance, we have a GetLink() static method on the base that returns the path the page (derived).

In AppCode

public class AdminHomeBase : Page

{

public static string GetLink() { return "~/Admin/main.aspx"; }

}

In Code File

public partial AdminHome : AdminHomeBase

{

}

Now in any ascx anywhere on the site you can make a link to the admin page

MyLinkNavigateUrl = typeof(AdminHomeBase).GetLink();

Nice to have a compile time check for all your page links isn't it?

CF