Click here to Skip to main content
15,889,116 members
Articles / Web Development / ASP.NET
Article

Object-Oriented ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.22/5 (26 votes)
10 Aug 20035 min read 185.5K   1K   58   30
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 the DataGrid. 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:

C#
<... 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:
C#
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:
C#
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:

  1. 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.
  2. 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 from DataGrid, 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:

Creating a DataGrid subclass

Once you have added your new derived class, we will go about customizing the behavior. First we need a way to determine which column is the Delete column in the grid. One approach is to override the DataGrid's CreateColumnSet method and examine the columns as they are created:
C#
// 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):

C#
// 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 derived DataGrid 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>:
HTML
<%@ 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:

C#
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 the Page objects.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAn easy way to bind 'DELETE confirmation message' to .NET controls Pin
elizas17-Feb-10 1:38
elizas17-Feb-10 1:38 
GeneralData Entry Forms Pin
Member 219117815-Aug-05 9:59
Member 219117815-Aug-05 9:59 
GeneralCustom Datagrid Pin
Michael Sync7-Dec-04 15:50
Michael Sync7-Dec-04 15:50 
Generalgetting at the datagrid items Pin
tristian o'brien23-Nov-04 5:30
tristian o'brien23-Nov-04 5:30 
GeneralProblem with multible Submit Buttons in One form Pin
dhanekula24-May-04 2:30
dhanekula24-May-04 2:30 
Generalthe active schema doesn not support Pin
ctcraig17-Sep-03 5:36
ctcraig17-Sep-03 5:36 
GeneralA sound framework lowers business costs - bring on OO Pin
apeterson20-Aug-03 2:57
apeterson20-Aug-03 2:57 
GeneralI have a question please... Pin
profoundwhispers19-Aug-03 4:17
profoundwhispers19-Aug-03 4:17 
GeneralRe: I have a question please... Pin
CBoland19-Aug-03 4:56
CBoland19-Aug-03 4:56 
GeneralRe: I have a question please... Pin
Anonymous19-Aug-03 8:39
Anonymous19-Aug-03 8:39 
GeneralRe: I have a question please... Pin
Los Guapos19-Aug-03 11:26
Los Guapos19-Aug-03 11:26 
GeneralAnother Silly OOP Purist and Fanatic Example Pin
rh200113-Aug-03 1:25
rh200113-Aug-03 1:25 
Ok, that's it. This is totally nonsense and OVERLY OOP.

Let's take a look at that REAL WORLD EXAMPLE of 5 pages with 5 datagrids.

Just how much time and money did you save by using OOP in this situation? I could have easily done a "SEARCH and REPLACE" in a tenth of the time you took to "FIGURE" out the object model.

Second, are each of the 5 pages going to be exactly the same and need the same features?

Third, YOUR ENCAPSULATION reasoning is TOTALLY FLAWED in the REAL WORLD. People, READ USERS, look at WEB PAGES, not objects. By tying your new Delete oop inherited method/class to all these pages, you also make it a lot harder to CORRECT mistakes while maintaining it a "FEW MONTHS" from now. WHY IS THIS SO? Because you made something SIMPLE, more COMPLEX and SCATTERED.

WHAT THEY DON'T SAY ON THE OOP MAINTENACE ADVANTAGE
This OOP maintenance advantage of making a single change doesn't work in the REAL WORLD, because you take 2 hours of even days to "re-familiarize" yourself with this modified and complex object model to make this 2 second change that never comes about. Plus, you have to check if anything else didn't break as well in the other 4 pages. so much for that 2 second change.



YOUR SO called ENCAPSULATION is NOW a SINGLE POINT OF FAILURE for all of those 5 web pages!!!
In the REAL world, one CANNOT predict if and how the business requirements will change and so some pages will not need this, or some pages will need more OR in reality "who knows what".

Let's put your OOP sillyness to the test in the REAL WORLD and do an ROI on it as well. I say, by the time your expensive OOP programmer has figured out and re-understands the object model that HE FORGOT a month ago, My average NON-OOP programmer, has already made the change not only to 5 pages but to say 50 pages via search and replace...and best of all, he can see which pages were changed. YOur oop programmer, still has to compile and RE-TEST the entire application because it broke the "if it works, don't mess with it" rule.

OOP is not the only tool and is NOT always the best tool to make global changes.

THIS FULLY OOP solution is just like the stupid newbie progammer fanactics who build fully normalized databases.

If your OOP was so GOOD, why does Microsoft with its 50,000 employees still have bugs in its programs and constant almost daily updates.

WHERE is THAT OOP ENCAPSULATION when those SERVICE PACKS come OUT and when installed starts to break things that were previously fixed? Or adds new bugs to the system.

WARNING:
I got plenty more examples, news articles and just HARD HITTING and PURE LOGIC to put these OOP fanatics in their place.



GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Los Guapos13-Aug-03 1:34
Los Guapos13-Aug-03 1:34 
GeneralBjarne Stroustrup != GOD Pin
rh200113-Aug-03 10:18
rh200113-Aug-03 10:18 
GeneralRe: Bjarne Stroustrup != GOD Pin
Los Guapos13-Aug-03 11:26
Los Guapos13-Aug-03 11:26 
GeneralRe: Bjarne Stroustrup != GOD Pin
rh200113-Aug-03 11:52
rh200113-Aug-03 11:52 
GeneralRe: Bjarne Stroustrup != GOD Pin
MammaMu19-Aug-03 11:11
MammaMu19-Aug-03 11:11 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
cas413-Aug-03 2:26
cas413-Aug-03 2:26 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
WittnezZ (Claus Witt)13-Aug-03 3:11
WittnezZ (Claus Witt)13-Aug-03 3:11 
GeneralDear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
rh200113-Aug-03 10:04
rh200113-Aug-03 10:04 
GeneralRe: Dear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
Anonymous13-Aug-03 19:31
Anonymous13-Aug-03 19:31 
GeneralRe: Dear OOP Fanatics, OOP != Holy Grail ; Comprende? Pin
rh200113-Aug-03 22:02
rh200113-Aug-03 22:02 
GeneralOO != Grail? Then what, pray tell... Pin
wik18-Aug-03 16:55
wik18-Aug-03 16:55 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Wilco B.16-Aug-03 2:40
Wilco B.16-Aug-03 2:40 
GeneralRe: Another Silly OOP Purist and Fanatic Example Pin
Oskar Austegard18-Aug-03 13:19
Oskar Austegard18-Aug-03 13:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.