In this article, we shall learn how to create a user control and use it in the content pages or master pages.
As per this post
, A user control is a user-authored server control that enables an ASP.NET page to be re-used as a server control. An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class.
In order to create a new user control, right click the project and select “Web User Control” (.ascx file) from the dialogue box as displayed in the picture below.
ASCX Page (USER CONTROL)
Keep some links or other content you want to keep in the user control. In my case I have kept some links in this page.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl" %>
<div style="background-color: #f0f0f0; padding: 5px;">
<a href="Default.aspx" title="Home">Home</a> | <a href="Page1.aspx" title="Page 1">Page
1</a> | <a href="Page2.aspx" title="Page 2">Page 2</a>
<hr /> </div>
<%@ page language="C#" autoeventwireup="true" codefile="Copy of Default.aspx.cs"
<%@ register src="~/MenuControl.ascx" tagprefix="uc1" tagname="Menu" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<head id="Head1" runat="server">
<form id="form1" runat="server">
<uc1:Menu runat="server" ID="Menu1" />
In the above code snippet, we have kept some hyperlinks (anchor tags) in the .ascx (user control) page. We can keep any number of html or asp.net server controls onto the user control. In the .aspx page we have registered the user control using the Register directives where
- Src is the path of the .ascx page (user control)
- TagPrefix is the namespace we want to associate for this control – it can be any string
- TagName is the name we want to associate for this control – it can be any string
To use this tag, we can keep the
TagPrefix of the registered user control on the .aspx page as we do for normal asp.net server controls and the content of the user control shall appear on the page as displayed in the picture below.
In the same way we can use this User control in the master page as well.
Hope this simple article should help the beginners. Stay tuned for the next article in this series.
Thanks for reading.