Posted on

Sharing a Class In ASP.NET Pages

It’s easy enough to create additional classes that can be used in the code behind files of an ASP.NET page, but what if you want to share a class among the ASP pages themselves? It’s quite common and easy to develop generic methods and event handlers that can reduce repetition of code and simplify the process of creating the different parts of your UI. In a recent project, I needed to create such a class and make it available to all my ASP pages. The class contained two methods that were meant to be called by the DataBind event of a GridView or DetailView in order to assign Javascript confirmations to all the Delete Commands and looked something like this…

namespace ProjectNameSpace {

 public class AdminUI {

 public void add_delete_confirmations_to_grid_view(object sender, EventArgs e)
 // Do stuff

 public void add_delete_confirmations_to_detail_view(object sender, EventArgs e)
 // Do stuff

Now that we have the class, we need to find the way to make it available to our ASP pages. The usual way to do this is via an entry in the web.config that makes the namespace available like this….


…which works fine if you intend on calling the method using ASP tags…

<% AdminUI.add_delete_confirmations_to_grid_view(); %>

…but the methods above aren’t mean to be used in ASP tags. They are meant to be assigned directly to events of ASP Controls like so…

<ASP:GridView OnDataBoundEvent="AdminUI.add_delete_confirmations_to_grid_view">

…which sadly, does not work. This seems to be something that was overlooked in ASP.NET. The former compiles, but the latter generates a “AdminUI namespace not found” type of error.

So in order to get around that, we are going to have to make use of inheritance.

Normally, the code behind classes for an ASP page are children of the System.Web.UI.Page like this….

public partial class Users : System.Web.UI.Page { }

Therefore, I can construct my AdminUI class as a middle layer between my ASP classes and System.Web.UI.Page by changing AdminUI to…

public class AdminUI : System.Web.UI.Page {}

… and all of my ASP classes to something like this…

public partial class Users : AdminUI { }

… and the assignment of the methods to their corresponding events becomes this…

<ASP:GridView OnDataBoundEvent="add_delete_confirmations_to_grid_view">

…and it works perfectly. All the methods that normally would have to be duplicated in multiple code behind files are in a centralized location and inherited by all of the classes so they can be used directly in the ASP pages without triggering a compiler error.