ASP.NET ships with a lot of controls, but sometimes, they aren’t enough for specific needs. Luckily, the ASP.NET control model is easily extendible. You can create your own controls in two ways:
- Create a Custom Control
- Create a User Control.
In this post (and in the exam, hopefully) you will need to be familiar only with the latter. A User Control is much like a standard aspx page. You use existing controls to build up your user interface, then write the code behind classes.
However, there are some differences as well:
- The file name extension is .ascx
- There is no @Page directive, but a @Control
- They cannot be run by themselves, only within an aspx page
- Html, body, head and form tags are forbidden in User controls
You can add a User control to your page two ways: register it, or set a reference on it. It is a better approach to use the register method. If you just set a reference on a User control, you’ll only be able to dynamically add it in your code-behind file. But let’s see how to do it:
HTML forms exist to collect data from the user. And this data, like every piece of user input, needs to be checked first for both security and logical reasons (what could we do with irrelevant data). There are two ways of checking the validity of user input: on the client side, and on the server side. Client side validation is swifter and more elegant, then posting back the data to the server, and the send back and error message. But we must implement both validation techniques, because a crafty attacker can bypass our client-validating methods, and send for example scripts or SQL commands back to our page to process them.
In order to understand the process of loading user controls in a dynamic manner, we should inspect the ASP.NET page life cycle. ASP.NET pages have a very short lifespan, due to their stateless HTML-based nature. Their life begins when somebody makes a request for them to the server. Then the page goes through the following stages:
- Request stage: compile page (if not precompiled), or pull from cache (if available)
- Start stage: set Response and Request, determine IsPostBack
- page_init: initialize page controls (without the associated properties), set page theme
- page_load: if the request is a PostBack, loads the control properties from the ViewState
- Validation: determines the validity of the page and its controls
- PostBack event handling stage: call event handlers
- page_render: saves the values to the ViewState, renders the controls and the output
- page_unload: cleanup stage, then discard
If you want to memorize this, use SILVER: Start Init Load Validate Events Render.
So far for the page life cycle, but when should we load dynamic controls? The answer hides in the page life cycle events. Table: