ASP.NET UserControls that are AWESOME: Using Events, properties, and methods.

by 28. September 2009 07:21

UserControls are underused
I am always shocked to see how little UserControls are used by some ASP.NET developers. To me, the UserControl is where a bulk of the real power in ASP.NET is. It took me a long time to get really used to using them, coming from a Classic ASP background, the loss of Server Side Includes was not easy to get used to. Thankfully, UserControls gave me back a commanding portion of the functionality I needed.

A Better Model / View / Controller
It’s really difficult to implement an MVC pattern in ASP.NET that I can look at and be proud of. Most of the implementations I have seen are very restrictive frameworks that require a lot of adherence to naming conventions, use of ISAPI filters, XML documents that have to be manually maintained as db or class structure changes, problems with Medium / Low Trust environments, and big performance losses.

ASP.NET, I think, had MVC in mind when they developed the paradigm in which they expect pages to operate, but they sure put a boatload of tools in to derail that. Your .aspx page is your view, unfortunately, they tightly coupled a controller (aspx.cs, code-behind) to every view, to the point they are almost synonymous. Then the model, ugh.. you SHOULD be writing a model and a controller to be changing the views, but with WONDERFUL tools like the SqlDataSource, and XmlDataSource they promote bypassing the use of a model or data-layer, and promote addition of business logic in the code-behind. I’m not going to go on about this...

While what you see in my example is certainly not an MVC solution, but it will get you closer to a good and flexible pattern that you can rely on.

UserControls vs. ServerControl

UserControls are not ServerControls and vice-versa. A UserControl is a .ascx(.cs) file and for all shapes and purposes functions very similar to a .aspx(.cs) page. It has a similar life-cycle, and similar properties. The difference is that a ServerControl is typically a small, contained, piece of functionality ... think of a TextBox, or a Button control. ServerControls are usually an element made for a narrowed purpose. A UserControl on the other hand is typically a collection of controls for a specific business purpose. In short, if you extended a TextBox to use specifically for a first name you could put built-in usage and length rules, etc. Great example of a ServerControl. Comparatively, if you wanted a reusable login form for your website, that is something that you would want as a UserControl. UserControls are typically specific to the project or solution, and are very flexible. This is what we will focus on.

Explaining The Code
This would be a good time to download the .ZIP file and get into the code:

The web-app is a basic phonebook, there is no database, all of the entries are stored in a hashtable in Session.

Default.aspx - This is the main view. The UserControls are registered at the top of the .aspx file. In the CodeBehind you will see one method, and that is the EventHandler for one of the UserControls.

/controls - Folder for UserControls

/controls/ViewDataControl.ascx - This control is used for just SHOWING the data, really just contains a gridview. The CodeBehind contains several methods, the public “Refresh” method is the important one because that is exposed in order for the data in the control to be reloaded.

/controls/AddControl.ascx - This is the big one. This UserControl is the form where a person will add a new name to the phonebook. There are a few very important key points to note:
This control contains two properties. They allow abstracted access to the TextBox’s .Text properties. This allows the .ASPX page to read values from the form directly whenever it needs to.
This control contains a public DELEGATE and a public EVENT. This event is fired when the “add” button is pressed. This is how we are able to notify the .ASPX page that something has happened

/App_Code/PhoneBookDataHandler.cs - This class is what actually interacts with the Session data (the hashtable). We break logic like this out from the .ascx.cs and .aspx.cs  files because these functions are universal to the application. the aspx.cs and ascs.cs files SHOULD NOT (not just in this app, either) contain business logic. Those files are there to control the rendering of the page. I said above that I believe these files were also intended to be “controllers” for some perversion of an MVC pattern.

Back to the Default.aspx(.cs) files. - You can probably now see how the Default.aspx page is just the glue that holds the whole thing together. It’s nothing more than a conductor for the UserControls. The UserControls are put on the .aspx page, we then tell the .aspx page that when AddControl.ascx’s “OnEntryAdded” event fires, run the .Refresh() method on ViewDataControl.ascx. ViewDataControl.ascx then grabs the data from Session and puts it in the GridView.

WTF is Business Logic?
Many applications are written for a certain purpose, industry, or business. For this reason the “entities” (like a customer number) adhere universally to certain rules, and those rules have to be validated throughout the application. You do not want that type of logic repeated every time you have to do that, you just want to call a method that does it for you.

You will need to view the code to understand this, most likely. I recommend viewing in this order:

  • Default.aspx
    • Look at the UserControls being registered at the top of the page
    • Look at Line 16 where we tell the OnEntryAdded event to be handled by the method ucAddControl_EntryAdded
  • Default.aspx.cs
    • Look at the ucAddControl_EntryAdded method. All it does is run the .Refresh() method on the ViewData UserControl
  • ViewDataControl.ascx.cs
    • Notice the methods to get data simply ask the PhoneBookDataHandler class for the data.
    • View PhoneBookDataHandler.cs if you want to see the interaction with Session and the HashTable, but it’s not critical to understanding the UserControls.
  • AddControl.ascx
    • Just take a look at what controls are on the page, the text-boxes and buttons. The RequiredFieldsValidators are irrelevant to the tutorial.
  • AddControl.ascx.cs
    • This is the most important file of the entire tutorial.
    • Lines 19 & 20
      • Public properties that allow read-only access to the TextBox’s .Text property
    • Line 26
      • The delegate that defines the signature of the event
    • Line 32
      • The Event that broadcasts when an entry is added
    • Line 43
      • VERY IMPORTANT: This method is what actually fires the event.
    • Line 56
      • Just the button-click event handler. Calls methods that add the data, then fires the event.


I hope this helps you write awesome apps!

-Mike

AwesomeUserControls.zip (7.31 kb)

Tags: , , , , , ,

.NET | Development | How To


RecentComments

Comment RSS