|
Build an ASP.NET Server Control
Create a cross-application form for user logins and password changes.
by James Horan
Posted September 30, 2003
Technology Toolbox: C#, ASP.NET
One of my first serious ASP.NET challenges was a project to develop a generic login form that any application at my client's site could use. A successful login needed to return a User object the calling application could use to get information about a verified use, and a failed login needed to return an error. The most effective and elegant solution was to create a custom ASP.NET server control. This under-publicized functionality of ASP.NET lets you create dynamic, cross-application forms. I'll walk through creating a generic login custom server control as an example of how you can take advantage of server controls in your ASP.NET apps (download the source code).
ASP.NET server controls are controls you use all the time, such as Labels and TextBoxes. You can create a custom ASP.NET server control under two scenarios. You can subclass an existing server control to add functionality—for example, create a class that inherits from TextBox and adds validation functionality. Or, you can create a class that doesn't inherit from a specific control, but is a brand-new control that can (and usually does) contain many more than one existing server control. The solution you'll implement for this article uses the second approach.
The first step is to create a simple User class that contains three properties for the user: UserName, UserID, and Email (see Listing 1). Your server control passes this object back to the calling application if the user logs in to the system successfully.
Here's the class definition for the login server control (see Listing A for the control's complete code):
public class LoginForm : Control,
INamingContainer
The control inherits from the Control class to allow you to treat the LoginForm class as a server control and override the CreateChildControls method (I'll look at that in a bit). It also inherits the INamingContainer interface, which ensures that no naming conflicts occur between controls in the server control and controls in the calling application's pages.
Back to top
|