Monday, 17 October 2011

ASPX vs ASCX (ASP.NET Page vs User Control)

A lot of web developers while learning ASP.NET get confused with the difference between an ASP.NET Page and ASP.NET User Control.
A User Control is a group of one or more ASP.NET Server Controls or HTML Controls that can be reused. So for example if you need to create a Login Control, you would group a bunch of TextBoxes, Label and Button Controls and create a User Control out of it. This User Control can then be reused on multiple pages, providing a Modular approach to web development.
User Control are similar to ASP.NET Web Pages (WebForm). User Control can have markup, code and script, just like Web Pages have. Since both the User Control and ASP.NET Web Page inherit from the TemplateControl class, they also share common methods and events.
However there are some basic differences between the two:

ASP.NET User Control
ASP.NET Page uses the extension .aspx For eg: Default.aspxUser Control uses the extension .ascx For eg: WebUserControl.ascx
ASP.NET Page begin with a Page Directive. For eg:
<%@ Page Language="C#"
Inherits="_Default" %>

User Control begin with a Control Directive. For eg:

<%@ Control Language="C#"
Inherits="WebUserControl" %>

ASP.NET Page can be viewed directly in the Browser.User Control cannot be viewed directly in the browser. User Controls are added to WebPages and you view them by requesting a web page in your browser.
ASP.NET Page has a HTML, Body and Form ElementUser Control does not have a HTML, Body or Form element. It is hosted inside an ASP.NET Page.