Object-Oriented ASP.NET






4.22/5 (23 votes)
Aug 11, 2003
5 min read

188629

1047
Use the powerful object-oriented features of C# and VB.NET to build re-usable classes in ASP.NET
Introduction
ASP.NET brings a whole new world of functionality, power, and ease of rapid development for web programmers. Some of these features, such as the advent of code-behind, are well documented and have become standard practice in everyday development. Another feature ASP.NET brings us is development with a real, compiled language. We can now leverage the object-oriented aspects of these new languages and put them to work in our code. We can take advantage of inheritance, polymorphism, and encapsulation when writing web apps while still maintaining an Microsoft DNA-style n-tier architecture.
I'm not going to try to explain these OO design concepts because they are already the subject of a great many articles (and books). For example, you could try this article right here on CP for an introduction.
I will be showing a simple example of how you can use inheritance and encapsulation in ASP.NET. I will show how you can customize a datagrid by encapsulating some behavior in a subclass of the datagrid, and thereby making the derived DataGrid
class re-usable across multiple forms or applications. I'll be using C# for this example, but the same principles apply to VB.NET.
A Real-World Example
For this example I will be using a common scenario developers encounter with theDataGrid
. The DataGrid
gives us some powerful pre-built column objects, including command columns which allow the user to press buttons (or links) to select, edit, or delete items in the grid. Imagine you are writing a web form which uses a DataGrid
having a "Delete" column, and you want to make the user confirm the deletion before actually deleting the item.
This is accomplished by using some client-side javascript to invoke the confirm
function in the onclick
handler:
<... onclick="return confirm('Are you sure?');" >
The way that you attach this code to the Delete button is to add to the item's Attributes
collection when the item is created: Control.Attributes.Add("onclick", "return confirm('Are you sure?')");
You will typically find code like this in the Page
class which is handling the OnItemCreated
event of the grid. It usually goes something like this: private void InitializeComponent()
{
this.grid.ItemCreated +=
new System.Web.UI.WebControls.DataGridItemEventHandler(
this.OnItemCreated);
// ...(other handlers)...
}
private void OnItemCreated(object sender,
System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==
ListItemType.AlternatingItem)
{
Button btn = e.Item.FindControl("delbutton");
btn.Attributes.Add("onclick", "return confirm('Are you sure?')");
}
}
I find this approach to be flawed for two reasons:
- Encapsulation is being violated. Why is it the job for the
Page
object to fiddle around with the internal attributes of the datagrid? It would be ideal if the page object could simply set a boolean property to enable the confirmation message box. - If you want to have delete confirmations for all 5 grids in all 5 pages of your application, you are going to have to repeat at least some of this code 5 times in your page classes. You can try to work around this by sharing some common code, but you still have to hook up an event handler for each grid in each page's
InitializeComponent
.
A Better Way
We will derive a new class fromDataGrid
, called ConfirmDelDataGrid
. The derived class will internally handle the code to attach the javascript attributes. In order to take advantage of deletion confirmation, the page class merely has to create an instance of ConfirmDelDataGrid
and do nothing else.
Creating a Derived DataGrid
To create the new customized DataGrid, right click on your project in the Class View and select "Add... Class". You must be in the class view! If you try this in the solution explorer, you can only add generic classes to your project. Type a class name and then switch to the Base Class panel. Select the DataGrid as your base class, like this:DataGrid
's CreateColumnSet
method and examine the columns as they are created: // Class member that stores the index of the "Delete" column of this grid
protected int delcol = -1;
protected override ArrayList CreateColumnSet(PagedDataSource dataSource,
bool useDataSource)
{
// Let the DataGrid create the columns
ArrayList list = base.CreateColumnSet (dataSource, useDataSource);
// Examine the columns
delcol=0;
foreach (DataGridColumn col in list)
{
// If this column is the "Delete" button command column...
if ((col is ButtonColumn) &&
(((ButtonColumn)col).CommandName == "Delete"))
{
// Found it
break;
}
delcol++;
}
// If we did not find a delete column, invalidate the index
if (delcol == list.Count) delcol = -1;
// Done
return list;
}
By overriding the CreateColumnSet
method we get a chance to examine the columns right after they are created by the DataGrid
base class. We figure out which column (if any) is the "Delete" column and store that index in a protected member variable.
Next we will override the OnItemDataBound
method of the DataGrid base class. First we let the DataGrid
bind the item, then we attach the javascript to the delete column (if any):
// Property to enable/disable deletion confirmation
protected bool confirmdel = true;
public bool ConfirmOnDelete
{
get { return confirmdel; }
set { confirmdel = value; }
}
protected override void OnItemDataBound(DataGridItemEventArgs e)
{
// Create it first in the DataGrid
base.OnItemDataBound (e);
// Attach javascript confirmation to the delete button
if ((confirmdel) && (delcol != -1))
{
e.Item.Cells[delcol].Attributes.Add("onclick",
"return confirm('Are you sure?')");
}
}
So that is the code internal to the DataGrid
. Notice that the new behavior is built-in to the class and a Page object who uses the class does not need to do anything to enable the deletion confirmation message box.
Putting it All Together
Now comes the beautiful part. Once we have created our derivedDataGrid
class called ConfirmDelDataGrid
, using it and leveraging its new built-in functionality is a snap. First, add a @Register
tag on the .aspx page to register the datagrid class and use it rather than <asp:DataGrid>
: <%@ Register tagprefix="dg" Namespace="ooaspnet" Assembly="ooaspnet" %>
<!-- (page layout & design here)... -->
<dg:ConfirmDelDataGrid id="grid" runat="server" ..... >
<dg:ConfirmDelDataGrid>
You'll also need to set the code-behind in your .cs file to use the new derived class:
protected ConfirmDelDataGrid grid;
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
grid.ConfirmOnDelete = true;
grid.DataSource = new string[4] { "red", "green", "blue", "purple" };
grid.DataBind();
}
}
This is as simple as it gets. We have a new DataGrid
subclass with a property that lets us automatically add confirmation message boxes, without knowing (or caring) at the Page
level how it works.
Also, if we ever decide to improve the code for attaching the javascript, we can just modify the code inside the ConfirmDelDataGrid
class once. Every page that uses this class will automatically benefit from the changes.
Conclusion
Programming ASP.NET allows us to take advantage of the powerful features of the underlying languages that we use. We can use object-oriented design features such as inheritance and encapsulation to develop re-usable classes that work autonomously and do not require glue code on thePage
objects.