We all know the benefits of re-usable components in our applications and User Controls in ASP.Net are an easy way to build reusable components that can be used throughout an entire web application.
Templated User Controls allows us to seperate the controls data from it’s presentation because a Templated User Control does not provide a default user interface.
For example I will show you how to create a templated address control thats allows you to reuse address fields across your web application but leaves the formatting up to the individual page designer to style how they wish.
First we open a new web application in Visual Studio and add a new Web User Control to our solution.
We then add a PlaceHolder control to the User Control which will act as a placeholder for our controls rendered data. Our controls markup looks like this:
Next we switch to our controls code behind and implement all the properties we need for our address control plus one other property that returns a type of ITemplate. Our code behind looks like this:
Now we need to create a container class that will act as our naming container and exposes all the properties of the User Control to the host page. The container class needs to inherit from the Control class and implkements the INamingContainer interface. The class looks like this:
We need to put the following code inside out controls Init event to instantiate our container class and set its properties, instantiate a copy of the controls ITemplate inside the container control and add our container control to the PlaceHolder”s controls collection.
Now we have a fully working Templated User Control we can put this control onto any web page within out web application and set its data. The markup below shows how this is done:
And thats it!
If you want to do the same as this but package the control up into an assembly that can be reused across multiple web applications you need to create a control that inherits from the Control or WebControl class.