Visual C#. NET 2003 Unleashed
|
If you have already worked with HTML, you should be familiar with controls such as the text box, buttons, check boxes, radio buttons, and so forth. Each of them is represented on a web page as a visual control. These HTML controls are processed completely on the client side of a web application. So, only the browser can work with and represent them. But you could make these controls available to the server side of an application by adding one attribute: runat. You set the value of this attribute to server. In this case, on the server side of the application, you could have access to these controls through variables. So, you could access all public properties and methods of these variables. After you've finished using these controls, they generate HTML code that is included in the content of the HTML page generated by the server. Notice that each HTML element has a corresponding control on the server side. The following example shows how to transform a client-side control to server side: Client-side: <div > </div> Server-side: <div runat="server" > </div>
Transformation has been achieved in a very easy way: by adding the parameter runat="server". In the preceding example, the server creates a variable of the type HtmlGenericControl. When the client requests a page, ASP.NET generates the necessary HTML code for representing this control as div. As soon as you change a control to be managed on the server side, you can use all its public properties and methods to manage it. For example, you can change text that should be represented inside this element by using property InnerText: MyDiv.InnerText = "Some Text"; NOTE Notice that all HTML server controls are located in the namespace System.Web.UI.HtmlControls.
The following list contains all HTML controls that are available for use in .NET:
There is another type of control that can be used by server-side code: web server controls. Web server controls are very similar to HTML server controls. They are created on the server side and enable you to design complex interfaces with an advanced look and feel. It is obligatory to set the attribute runat="server" in the declaration of a web server control. If you do not set this attribute, the web server control will not be shown on the browser, nor will it be accessible to server-side code. Web server controls do not always corresponded to an HTML element. They could contain complex HTML constructs with complex business logic. Also they could contain other HTML and nested web server controls (this approach is very often used in the development practice). Let's discuss how to declare web server controls in web pages or other controls. The following example demonstrates how to declare text box web server control: <asp:TextBox Css name="searchRequestTextBox" MaxLength="30" Width="100%" Runat="server"></asp:TextBox> On the page, this element represents a text box that is called searchRequestTextBox that has a max length equal to 30 characters, and a width equal to 100%. The CSS class of this control is set to "control". Work with web server controls on the server side is very similar to work with HTML server controls. They are created at the server side and are available for developers through variables (instances of web server controls' classes). As mentioned earlier, these variables enable you to use all public properties and methods that are declared inside. NOTE Notice that each web server control has been rendered into ordinary HTML code before it was transferred to the browser. So, if you take a look at the HTML passed to the browser, you will not find anything unusual. You will see just simple HTML code. The purpose behind this is to give you extensive ability to choose what is rendered to the client by manipulating server-side objects. The following list contains the most commonly used web server controls that are provided by ASP.NET:
User Controls
An ASP.NET user control is a group of one or more server controls or static HTML elements that encapsulate some functionality. The power of a user control comes from ASP.NET treating the user control as a standalone object. The user control is presented as a separate class in the code-behind so that other classes in your application can interact with it indirectly by using its public methods and properties. For developers, this approach has greatly simplified the process of creating web applications. The main idea is to give developers the possibility of using a control as a simple class. In terms of how ASP.NET handles user controls, you can think of them as mini-pages. Each user control has its own sequence of events that take it through the process of rendering output. One of the ways in which you can create custom controls is to inherit your own control from an existing ASP.NET control just to extend its functionality. For example, assume that you want to have some additional functionality related to the representation and behavior of HTML input text box. You could create your own class, extend it from System.Web.UI.WebControls.TextBox, and implement your own additional functionality. Another way to create custom controls is by aggregating existing controls and/or simple HTML elements inside your own. For example, you might want to create some kind of questionnaire that could be used in several applications or several different places within the same application. The best way is to implement your own web control that will contain several existing controls (check boxes, combo boxes, images, text boxes, and so on) and encapsulate all logic related to the questionnaire. After you've created your own control, you could use it in different parts of your application, in different applications, insert it in different places during the design process, or use it dynamically as well as in predefined ASP.NET controls. So, you could customize your functionality and GUI, and make your application unique. NOTE Developers often ask what the difference is between user and server controls. User and server controls are very similar, but there is one essential difference. A server control is compiled in a DLL file and cannot be edited on an interactive design surface. However, you can manipulate it by using its public methods and properties at runtime. It is possible to build a custom server control (sometimes called a custom control or a composite control). In contrast, a user control consists of previously built server controls. It has an interface that can be completely edited and changed using the ASP.NET visual design surface. It can be manipulated at design time and runtime via properties that you are responsible for creating. Although third-party vendors will build a multitude of controls for every possible function of ASP.NET, they will exist in the form of compiled server controls, as mentioned earlier. Now that you have a good foundation, you can get to the coding of a custom control. This control will encapsulate some kind of help system. It will contain an area with some information and a search text box (see Figure 22.1). Figure 22.1. Sample interface using a custom control.
NOTE Note that this chapter will not explain how to set up the environment for working with a web application in .NET. All examples in this chapter assume that you are already familiar with IIS (how it works, and how it could be set up and configured) and the process of creating a web application. If you are uncertain in those areas, you should read additional articles related to setting up web applications in .NET.
Listings 22.122.4 present the HTML and source code of a web page and the custom user control that the web page uses. Listing 22.1. HTML Code of the Web Page
[View full width] <%@ Page language="c#" Codebehind="Main.aspx.cs" AutoEventWireup="false" Inherits="UserControlSample.Main" %> <%@ Register TagPrefix="UserControl" TagName="Help" src="/books/1/238/1/html/2/help.ascx"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>Main</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form method="post" runat="server"> <div align="center"> <table width="40%"> <tr> <td> <UserControl:Help runat="server"
Listing 22.2. The Source Code (Code Behind) of the Sample Web Page
[View full width] using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace UserControlSample { public class Main : System.Web.UI.Page { protected UserControlSample.Help HelpControl; private void Page_Load(object sender, System.EventArgs e) { HelpControl.SearchRequest = HttpContext.Current.Request.Form.Get
Listing 22.3. HTML Code of Custom User Control
[View full width] <%@ Control Language="c#" AutoEventWireup="false" Codebehind="Help.ascx.cs" Inherits="UserControlSample.Help" TargetSchema="http://schemas.microsoft.com/ intellisense/ie5"%> <style type="text/css"> .control { BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid; FONT-SIZE: 12; FONT-FAMILY: Verdana, Arial; } .text { BORDER-RIGHT: #000000 1px solid; BORDER-TOP: #000000 1px solid; BORDER-LEFT: #000000 1px solid; BORDER-BOTTOM: #000000 1px solid; FONT-SIZE: 12; PADDING: 3 3 3 3; FONT-FAMILY: Verdana, Arial; } </style> <table cellpadding="2" cellspacing="2" border="0" width="100%"> <tr> <td width="80%" align="left"> <asp:TextBox Css
NOTE Notice the lack of <BODY> tags. A user control does not need these tags because it will be placed on another page (or another user control) and rendered inline. The hosting page will be responsible for these common tags. The user control will, therefore, inherit all the host tags (including styles), unless they are specified otherwise.
Listing 22.4. Source Code of Custom User Control
[View full width] using System; using System.Data; using System.Drawing; using System.Collections; using System.Web; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace UserControlSample { public class Help : System.Web.UI.UserControl { protected HtmlGenericControl topicBody; protected HtmlGenericControl topicName; private void Page_Load(object sender, System.EventArgs e) { if (this._helpInformation != null) { if (_searchRequest != "" && _searchRequest != null) { IEnumerator enumerator = _helpInformation.Keys
This control contains an information area that displays the name of some topic and description for it. Also, the control contains a Search button and a text box in which you could enter your search request. The control is built by way of aggregation of existing ASP.NET server controls. So, let's discuss the process of control creation and implementation. To create a user control, you need to add a user-control file to a project.
The web project contains the web page Main.aspx. Let's include the control inside it. In the HTML code of the Main.aspx web form, you could find the following line: <%@ Register TagPrefix="UserControl" TagName="Help" src="/books/1/238/1/html/2/help.ascx"%>
The @ Register directive registers the control on the page. After the control has been registered on the page, you can freely add many instances of the controls to the page. The TagPrefix attribute specifies the prefix to use for the control(s). It is sort of like a namespace in which several controls might share a single prefix value. This is why all ASP.NET server controls specify the <asp: prefix. The only difference is that the ASP.NET server control directive is implied and not explicitly declared. TagName specifies the name of the control. Together, the tags create an instance of the control specified at the location of the Src attribute. You must also include the runat="server" name/value pair to manipulate the user control programmatically. Otherwise, only the raw HTML is sent back to the browser. Next, open the user-control file in HTML mode and put into it other HTML and Web controls. <asp:TextBox Css name="searchRequestTextBox" MaxLength="30" Width="100%" Runat="server"></asp:TextBox> <input type="submit" value="Search"/> <span runat="server" > </span> <div runat="server" > </div> This inserts in our custom control one predefined Web control (TextBox server control) and three HTML controls (one of them is also a server-side control). NOTE The Search button HTML control is not registered as a server control (without runat="server"). It's because we do not need to manage this control on the server side (to be more precise, we do not need to use its public properties and methods in the code behind). The searchRequestTextBox control is marked as runat="server", but is not used in the code behind because searchRequestTextBox is a web control (not an HTML control). All web controls should be marked with the runat="server" tag to be visible in the browser. If you don't mark a web control with that tag, it will not be shown on the browser and you will not be allowed to access to it in the code-behind.
Now that the HTML view of the control has been defined, you could start defining the code-behind of the control. The code in the code-behind works exactly the same as a web form. HTML will be rendered and sent to the browser exactly as if the user control's resulting HTML were simply pasted into the hosting page's markup. The sample code declares two public properties of the control (SearchRequest and HelpInformation). These properties will be used in the page or other web control where our control will be included. All logic of the control is concentrated on the Page_Load function. This code searches in keys of the help information dictionary for the first key that includes the requested string. The last step is to use the control in a web page or other control. How to register a user control in a web page has already been discussed. So, let's discuss how to use it in the code-behind of the page. In the code behind, the control is presented as a protected variable of type UserControlSample.Help. You could access all public properties and methods of this variable. The code initializes the Help control with the dictionary with some information and a search request that is retrieved from an HTTP request. You also could insert several Help controls on the same page and initialize them with different data (see Figures 22.4 and 22.5). Figure 22.4. The code-behind of the control.
Figure 22.5. Example of different Help controls.
|
|