Custom Controls Versus User Controls

Custom Controls Versus User Controls

In Chapter 9, you learned how to build your own user controls to encapsulate frequently used pieces of your ASP.NET pages. Custom controls serve a purpose that is very similar to user controls, and in fact often you will find that the same task could be accomplished using either a user control or a custom control. User controls are designed to be used for large sections of your ASP.NET pages, and in fact they were originally going to be named Pagelets. User controls are typically easier to build and deploy than custom controls, because you can place all your HTML logic and other controls into the .ascx file, and you can deploy the user control without having to compile it first. Custom controls, on the other hand, must handle all their user interface logic programmatically, and must be compiled into assemblies and distributed before they can be used.

Writing a custom control of your own in an editor like Visual Studio.NET usually requires more effort than writing a user control, since user controls have all the same visual designer support that ASP.NET pages (Web forms) have. However, once built, custom controls can be added to the visual designer toolbox and then dragged and dropped onto other pages, whereas user controls have less support with regard to designer integration (though this may change with the release version of Visual Studio.NET).

An additional benefit of custom controls is reuse across applications. User controls cannot be shared across application domains, and so if you have more than one Web application that could benefit from the same user control, your only recourse is to copy the control to every Web application that requires it. This makes updating the control a nightmare, because it must then be redeployed. A custom control can be deployed to individual applications, or it can be placed in the Global Assembly Cache (GAC) on the server, which will make it available to all applications on that server. The GAC is beyond the scope of this book to cover, and unless you are writing commercial controls, you typically will not need to install to the GAC. Another nice feature of Visual Studio.NET is that it allows you to add references to assemblies on your development machine. This makes sharing assemblies easy, since you can just drop them all in a common Assemblies folder, and then reference them as needed from various Web applications. Visual Studio.NET will then copy the needed assembly DLLs to the Web application's /bin folder whenever you compile the application.