Server Controls


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  >&nbsp;</div> Server-side: <div  runat="server" >&nbsp;</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:

  • HtmlAnchor Represents a hyperlink (<a> HTML element).

  • HtmlButton Represents the <input type="button"> HTML element. This control has many possibilities related to the behavior and view of the button. It is not supported by several browsers.

  • HtmlForm Defines an HTML form with all properties of it. Values of other controls are located inside it, and are sent to the server side after a submit action.

  • HtmlGenericControl Defines the base model of any HTML object (properties, methods, events, and so on). Each HtmlGenericControl control can be transformed to any HTML control.

  • HtmlImage Defines an HTML control that contains an image. It corresponds to the <img> HTML element.

  • HtmlInputButton Performs an action. This button is supported by all browsers. It corresponds to the <input type="submit"> HTML control. After you click this button, all data inside the form will be posted to the server.

  • HtmlInputCheckBox Creates a flag that supports two states: on and off. Also this element contains a caption property. HtmlInputCheckBox corresponds to the <input type="checkbox"> HTML element.

  • HtmlInputFile Enables users to upload files to the server. The form where this control is located should be configured to support this feature. Corresponds to the <input type="file"> HTML element.

  • HtmlInputHidden Represents a hidden text box that contains all auxiliary information about the form (some persistent data that should be always available in the form, but should not be visible to or edited by the user). Represents the <input type="hidden"> HTML control.

  • HtmlInputImage Very similar to a button control, but enables you to view a picture. Corresponds to the <input type="image"> HTML element.

  • HtmlInputRadioButton Represents a set of radio buttons. This control is normally employed for user selection as one of the available choices. Corresponds with <input type="radio">.

  • HtmlInputText Represents a text box that is initialized to a value that is set during development process. This control allows the user to edit text and post it to the server. Corresponds to <input type="text"> HTML element. Also, this control could be used as a password text box that corresponds to the <input type="password"> HTML element.

  • HtmlSelect Represents a list of items with markers (bullets, circles, squares, and so forth). Corresponds to the <select> HTML element.

  • HtmlTable Corresponds to the <table> HTML element and allows user to read and write a table's properties (add rows, add cell, change look and feel, and so on).

  • HtmlTableCell Creates one cell inside some table. Corresponds to the <td> HTML element.

  • HtmlTableRow Creates one row inside some table. Corresponds to the <tr> HTML element.

  • HtmlTextArea Represents area with text (something like a memo). This control is used to read and write large pieces of text. Corresponds to the <textarea> HTML element.

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:

  • Button Is used for performing some action. It's very similar to the HtmlButton HTML server control.

  • Calendar Represents graphical calendar and encapsulates its logic. You are allowed to select some date by using this control.

  • CheckBox Represents a flag, which could be checked or unchecked. The state of the check box is always sent to the server.

  • CheckBoxList Defines a group of check boxes and enables you to group check boxes with similar meaning.

  • DataGrid Represents some information (retrieved from a database or other data storage) that is formatted as a table with columns and cells. Allows the user to sort and edit data.

  • DataList Very similar to the Repeater control, but has more advanced possibilities for formatting and locating data. Also this control supports several modes of editing behavior.

  • DropDownList Enables user to select one item from a drop-down list or to type a custom item (like a text box).

  • HyperLink Creates a hyperlink.

  • Image Show image by the predefined path.

  • ImageButton Very similar to the Button web server control, but contains an image instead of text.

  • Label Contains read-only text (only for viewing).

  • LinkButton Similar to the Button control, but has a view like a hyperlink.

  • ListBox Creates a list of items. It enables you to select several items simultaneously.

  • Panel Creates part of a form that is a container for others controls.

  • RadioButton Represents a set of radio buttons. This control is normally used to select one of the available choices.

  • RadioButtonList Creates a group of radio buttons. Only one of elements can be selected inside one group.

  • Repeater Shows information that is retrieved from some data storage (such as a database). It uses other server controls, and repeats them for each record in the dataset.

  • Table Creates a table and enables the user to read and write the table's properties (add rows, add cell, change look and feel, and so on).

  • TableCell Creates one cell inside some table.

  • TableRow Creates one row inside some table.

  • TextBox Represents a text box that is initialized with a value that is set during development process. Allows the user to edit text and post it to the server.

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"  ></UserControl:Help>                                         </td>                                 </tr>                         </table>                 </div>     </form>   </body> </html> 

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 ("HelpControl:searchRequestTextBox");                         HelpControl.HelpInformation = HelpInformation();                 }                 #region Web Form Designer generated code                 override protected void OnInit(EventArgs e) {                         InitializeComponent();                         base.OnInit(e);                 }                 private void InitializeComponent() {                         this.Load += new System.EventHandler(this.Page_Load);                 }                 #endregion                 private IDictionary HelpInformation () {                         IDictionary helpInformation = new Hashtable();                         helpInformation.Add("abstract", "Use the abstract modifier in a  class declaration to indicate that a class is intended only to be a base class of other  classes.");                         helpInformation.Add("base", "The base keyword is used to access  members of the base class from within a derived class.");                         helpInformation.Add("break", "The break statement terminates the  closest enclosing loop or conditional statement in which it appears. Control is passed to  the statement that follows the terminated statement, if any.");                         helpInformation.Add("delegate", "A delegate declaration defines a  reference type that can be used to encapsulate a method with a specific signature. A  delegate instance encapsulates a static or an instance method. Delegates are roughly  similar to function pointers in C++; however, delegates are type-safe and secure.");                         helpInformation.Add("readonly", "The readonly keyword is a  modifier that you can use on fields. When a field declaration includes a readonly modifier , assignments to the fields introduced by the declaration can only occur as part of the  declaration or in a constructor in the same class.");                         return helpInformation;                 }         } } 

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   name="searchRequestTextBox" MaxLength="30" Width="100%" Runat="server"></asp:TextBox>                 </td>                 <td align="right">                         <input  type="submit" value="Search"/>                 </td>         </tr>         <tr>                 <td width="100%" colspan="2">                         <hr >                 </td>         </tr>         <tr>                 <td width="100%" colspan="2"><b><span runat="server" >&nbsp;< /span></b></td>         </tr>         <tr>                 <td width="100%" colspan="2">                         <div  runat="server" >&nbsp;</div>                 </td>         </tr> </table> 

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 .GetEnumerator();                                         string searchResult = null;                                         while (enumerator.MoveNext()) {                                                 if (enumerator.Current.ToString().IndexOf (_searchRequest) != -1) { searchResult = enumerator.Current.ToString();                                                         break;                                                 }                                         }                                         if (searchResult != null) {                                                 topicName.InnerText = searchResult;                                                 topicBody.InnerText =                                                 _helpInformation[searchResult].                                                 ToString();                                         } else {                                                 topicName.InnerText = "";                                                 topicBody.InnerText = ERROR_MESSAGE;                                         }                                 }                                 else {                                         topicName.InnerText = "";                                         topicBody.InnerText = EMPTY_MESSAGE;                                 }                         } else {                                 topicName.InnerText = "";                                 topicBody.InnerText = ERROR_MESSAGE;                         }                 }                 #region Web Form Designer generated code                 override protected void OnInit(EventArgs e) {                         InitializeComponent();                         base.OnInit(e);                 }                 private void InitializeComponent() {                         this.Load += new System.EventHandler(this.Page_Load);                 }                 #endregion                 public IDictionary HelpInformation {                         set {                                 if (value != null) {                                         this._helpInformation = value;                                 } else {                                         this._helpInformation = new Hashtable();                                 }                         }                 }                 public string SearchRequest {                         set {                                 this._searchRequest = value;                         }                 }                 private IDictionary _helpInformation;                 private string _searchRequest;                 private const string ERROR_MESSAGE = "No topics were found by your request.";                 private const string EMPTY_MESSAGE = "No request was entered.";         } } 

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.

1.

First, create a new C# ASP.NET Web application.

2.

Right-click on the project in the Project Explorer, click Add\Add New Item, and select a Web User Control item (see Figures 22.2 and 22.3). This adds a file with the extension .ascx to the project. This is the file that the user control will use to expose its interface. An ASCX file cannot be viewed directly in the browser. It must be placed within a container (such as another Web form) to be viewed.

Figure 22.2. Selecting a Web User Control item.


Figure 22.3. The Add New Item dialog box.


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" >&nbsp;</span> <div  runat="server" >&nbsp;</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.




    Visual C#. NET 2003 Unleashed
    Visual C#. NET 2003 Unleashed
    ISBN: 672326760
    EAN: N/A
    Year: 2003
    Pages: 316

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net