Header Ads Widget

ad728

ASP.NET (Part-2)


    First Example 

    An ASP.NET page is made up of a number of server controls along with HTML controls, text, and images. Sensitive data from the page and the states of different controls on the page are stored in hidden fields that form the context of that page request.

    ASP.NET runtime controls the association between a page instance and its state. An ASP.NET page is an object of the Page or inherited from it.

    All the controls on the pages are also objects of the related control class inherited from a parent Control class. When a page is run, an instance of the object page is created along with all its content controls.

    An ASP.NET page is also a server side file saved with the .aspx extension. It is modular in nature and can be divided into the following core sections:

    • Page Directives
    • Code Section
    • Page Layout

    Page Directives

    The page directives set up the environment for the page to run. The @Page directive defines page-specific attributes used by ASP.NET page parser and compiler. Page directives specify how the page should be processed, and which assumptions need to be taken about the page.

    It allows importing namespaces, loading assemblies, and registering new controls with custom tag names and namespace prefixes.

    Code Section

    The code section provides the handlers for the page and control events along with other functions required. We mentioned that, ASP.NET follows an object model. Now, these objects raise events when some events take place on the user interface, like a user clicks a button or moves the cursor. The kind of response these events need to reciprocate is coded in the event handler functions. The event handlers are nothing but functions bound to the controls.

    The code section or the code behind file provides all these event handler routines, and other functions used by the developer. The page code could be precompiled and deployed in the form of a binary assembly.

    Page Layout

    The page layout provides the interface of the page. It contains the server controls, text, inline JavaScript, and HTML tags.

    The following code snippet provides a sample ASP.NET page explaining Page directives, code section and page layout written in C#:

    <!-- directives -->
    <% @Page Language="C#" %>
    
    <!-- code section -->
    <script runat="server">
    
       private void convertoupper(object sender, EventArgs e)
       {
          string str = mytext.Value;
          changed_text.InnerHtml = str.ToUpper();
       }
    </script>
    
    <!-- Layout -->
    <html>
       <head> 
          <title> Change to Upper Case </title> 
       </head>
       
       <body>
          <h3> Conversion to Upper Case </h3>
          
          <form runat="server">
             <input runat="server" id="mytext" type="text" />
             <input runat="server" id="button1" type="submit" value="Enter..." OnServerClick="convertoupper"/>
             
             <hr />
             <h3> Results: </h3>
             <span runat="server" id="changed_text" />
          </form>
          
       </body>
       
    </html>

    Copy this file to the web server root directory. Generally it is c:\iNETput\wwwroot. Open the file from the browser to execute it and it generates following result:

    ASP.NET First ExampleASP.NET First Example

    Using Visual Studio IDE

    Let us develop the same example using Visual Studio IDE. Instead of typing the code, you can just drag the controls into the design view:

    ASP.NET First Example 2

    The content file is automatically developed. All you need to add is the Button1_Click routine, which is as follows:

    protected void Button1_Click(object sender, EventArgs e)
    {
       string buf = TextBox1.Text;
       changed_text.InnerHtml = buf.ToUpper();
    }

    The content file code is as given:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
       Inherits="firstexample._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    
       <head runat="server">
          <title>
             Untitled Page
          </title>
       </head>
       
       <body>
       
          <form id="form1" runat="server">
             <div>
             
                <asp:TextBox ID="TextBox1" runat="server" style="width:224px">
                </asp:TextBox>
                
                <br />
                <br />
                
                <asp:Button ID="Button1" runat="server" Text="Enter..." style="width:85px" onclick="Button1_Click" />
                <hr />
                
                <h3> Results: </h3>
                <span runat="server" id="changed_text" />
                
             </div>
          </form>
          
       </body>
       
    </html>

    Execute the example by right clicking on the design view and choosing 'View in Browser' from the popup menu. This generates the following result:

    ASP.NET First Example 3


     

    Event Handling

    An event is an action or occurrence such as a mouse click, a key press, mouse movements, or any system-generated notification. A process communicates through events. For example, interrupts are system-generated events. When events occur, the application should be able to respond to it and manage it.

    Events in ASP.NET raised at the client machine, and handled at the server machine. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server.

    The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler. If it has, the event handler is executed.

    Event Arguments

    ASP.NET event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is event argument.

    The general syntax of an event is:

    private void EventName (object sender, EventArgs e);

    Application and Session Events

    The most important application events are:

    • Application_Start - It is raised when the application/website is started.

    • Application_End - It is raised when the application/website is stopped.

    Similarly, the most used Session events are:

    • Session_Start - It is raised when a user first requests a page from the application.

    • Session_End - It is raised when the session ends.

    Page and Control Events

    Common page and control events are:

    • DataBinding - It is raised when a control binds to a data source.

    • Disposed - It is raised when the page or the control is released.

    • Error - It is a page event, occurs when an unhandled exception is thrown.

    • Init - It is raised when the page or the control is initialized.

    • Load - It is raised when the page or a control is loaded.

    • PreRender - It is raised when the page or the control is to be rendered.

    • Unload - It is raised when the page or control is unloaded from memory.

    Event Handling Using Controls

    All ASP.NET controls are implemented as classes, and they have events which are fired when a user performs a certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling events, there are in-built attributes and event handlers. Event handler is coded to respond to an event, and take appropriate action on it.

    By default, Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles.

    The ASP tag for a button control:

    <asp:Button ID="btnCancel" runat="server" Text="Cancel" />

    The event handler for the Click event:

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) 
    
       Handles btnCancel.Click
       
    End Sub

    An event can also be coded without Handles clause. Then, the handler must be named according to the appropriate event attribute of the control.

    The ASP tag for a button control:

    <asp:Button ID="btnCancel" runat="server" Text="Cancel" Onclick="btnCancel_Click" />

    The event handler for the Click event:

    Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    
    End Sub

    The common control events are:

    EventAttributeControls
    ClickOnClickButton, image button, link button, image map
    CommandOnCommandButton, image button, link button
    TextChangedOnTextChangedText box
    SelectedIndexChangedOnSelectedIndexChangedDrop-down list, list box, radio button list, check box list.
    CheckedChangedOnCheckedChangedCheck box, radio button

    Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click event such as, Button.Click.

    Some events are not posted back to the server immediately, these are called non-postback events.

    For example, the change events or selection events such as TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true.

    Default Events

    The default event for the Page object is Load event. Similarly, every control has a default event. For example, default event for the button control is the Click event.

    The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls:

    ControlDefault Event
    AdRotatorAdCreated
    BulletedListClick
    ButtonClick
    CalenderSelectionChanged
    CheckBoxCheckedChanged
    CheckBoxListSelectedIndexChanged
    DataGridSelectedIndexChanged
    DataListSelectedIndexChanged
    DropDownListSelectedIndexChanged
    HyperLinkClick
    ImageButtonClick
    ImageMapClick
    LinkButtonClick
    ListBoxSelectedIndexChanged
    MenuMenuItemClick
    RadioButtonCheckedChanged
    RadioButtonListSelectedIndexChanged

    Example

    This example includes a simple page with a label control and a button control on it. As the page events such as Page_Load, Page_Init, Page_PreRender etc. take place, it sends a message, which is displayed by the label control. When the button is clicked, the Button_Click event is raised and that also sends a message to be displayed on the label.

    Create a new website and drag a label control and a button control on it from the control tool box. Using the properties window, set the IDs of the controls as .lblmessage. and .btnclick. respectively. Set the Text property of the Button control as 'Click'.

    The markup file (.aspx):

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
       Inherits="eventdemo._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    
       <head runat="server">
          <title>Untitled Page</title>
       </head>
       
       <body>
          <form id="form1" runat="server">
             <div>
                <asp:Label ID="lblmessage" runat="server" >
                
                </asp:Label>
                
                <br />
                <br />
                <br />
                
                <asp:Button ID="btnclick" runat="server" Text="Click" onclick="btnclick_Click" />
             </div>
          </form>
       </body>
       
    </html>

    Double click on the design view to move to the code behind file. The Page_Load event is automatically created without any code in it. Write down the following self-explanatory code lines:

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    
    using System.Xml.Linq;
    
    namespace eventdemo {
    
       public partial class _Default : System.Web.UI.Page {
       
          protected void Page_Load(object sender, EventArgs e) {
             lblmessage.Text += "Page load event handled. <br />";
             
             if (Page.IsPostBack) {
                lblmessage.Text += "Page post back event handled.<br/>";
             }
          }
          
          protected void Page_Init(object sender, EventArgs e) {
             lblmessage.Text += "Page initialization event handled.<br/>";
          }
          
          protected void Page_PreRender(object sender, EventArgs e) {
             lblmessage.Text += "Page prerender event handled. <br/>";
          }
          
          protected void btnclick_Click(object sender, EventArgs e) {
             lblmessage.Text += "Button click event handled. <br/>";
          }
       }
    }

    Execute the page. The label shows page load, page initialization and, the page pre-render events. Click the button to see effect:

    ASP.NET Event Example


    Server Side

    We have studied the page life cycle and how a page contains various controls. The page itself is instantiated as a control object. All web forms are basically instances of the ASP.NET Page class. The page class has the following extremely useful properties that correspond to intrinsic objects:

    • Session
    • Application
    • Cache
    • Request
    • Response
    • Server
    • User
    • Trace

    We will discuss each of these objects in due time. In this tutorial we will explore the Server object, the Request object, and the Response object.

    Server Object

    The Server object in Asp.NET is an instance of the System.Web.HttpServerUtility class. The HttpServerUtility class provides numerous properties and methods to perform various jobs.

    Properties and Methods of the Server object

    The methods and properties of the HttpServerUtility class are exposed through the intrinsic Server object provided by ASP.NET.

    The following table provides a list of the properties:

    PropertyDescription
    MachineNameName of server computer
    ScriptTimeOutGets and sets the request time-out value in seconds.

    The following table provides a list of some important methods:

    MethodDescription
    CreateObject(String)Creates an instance of the COM object identified by its ProgID (Programmatic ID).
    CreateObject(Type)Creates an instance of the COM object identified by its Type.
    Equals(Object)Determines whether the specified Object is equal to the current Object.
    Execute(String)Executes the handler for the specified virtual path in the context of the current request.
    Execute(String, Boolean)Executes the handler for the specified virtual path in the context of the current request and specifies whether to clear the QueryString and Form collections.
    GetLastErrorReturns the previous exception.
    GetTypeGets the Type of the current instance.
    HtmlEncodeChanges an ordinary string into a string with legal HTML characters.
    HtmlDecodeConverts an Html string into an ordinary string.
    ToStringReturns a String that represents the current Object.
    Transfer(String)For the current request, terminates execution of the current page and starts execution of a new page by using the specified URL path of the page.
    UrlDecodeConverts an URL string into an ordinary string.
    UrlEncodeTokenWorks same as UrlEncode, but on a byte array that contains Base64-encoded data.
    UrlDecodeTokenWorks same as UrlDecode, but on a byte array that contains Base64-encoded data.
    MapPathReturn the physical path that corresponds to a specified virtual file path on the server.
    TransferTransfers execution to another web page in the current application.

    Request Object

    The request object is an instance of the System.Web.HttpRequest class. It represents the values and properties of the HTTP request that makes the page loading into the browser.

    The information presented by this object is wrapped by the higher level abstractions (the web control model). However, this object helps in checking some information such as the client browser and cookies.

    Properties and Methods of the Request Object

    The following table provides some noteworthy properties of the Request object:

    PropertyDescription
    AcceptTypesGets a string array of client-supported MIME accept types.
    ApplicationPathGets the ASP.NET application's virtual application root path on the server.
    BrowserGets or sets information about the requesting client's browser capabilities.
    ContentEncodingGets or sets the character set of the entity-body.
    ContentLengthSpecifies the length, in bytes, of content sent by the client.
    ContentTypeGets or sets the MIME content type of the incoming request.
    CookiesGets a collection of cookies sent by the client.
    FilePathGets the virtual path of the current request.
    FilesGets the collection of files uploaded by the client, in multipart MIME format.
    FormGets a collection of form variables.
    HeadersGets a collection of HTTP headers.
    HttpMethodGets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client.
    InputStreamGets the contents of the incoming HTTP entity body.
    IsSecureConnectionGets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS).
    QueryStringGets the collection of HTTP query string variables.
    RawUrlGets the raw URL of the current request.
    RequestTypeGets or sets the HTTP data transfer method (GET or POST) used by the client.
    ServerVariablesGets a collection of Web server variables.
    TotalBytesGets the number of bytes in the current input stream.
    UrlGets information about the URL of the current request.
    UrlReferrerGets information about the URL of the client's previous request that is linked to the current URL.
    UserAgentGets the raw user agent string of the client browser.
    UserHostAddressGets the IP host address of the remote client.
    UserHostNameGets the DNS name of the remote client.
    UserLanguagesGets a sorted string array of client language preferences.

    The following table provides a list of some important methods:

    MethodDescription
    BinaryReadPerforms a binary read of a specified number of bytes from the current input stream.
    Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from object.)
    GetTypeGets the Type of the current instance.
    MapImageCoordinatesMaps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values.
    MapPath(String)Maps the specified virtual path to a physical path.
    SaveAsSaves an HTTP request to disk.
    ToStringReturns a String that represents the current object.
    ValidateInputCauses validation to occur for the collections accessed through the Cookies, Form, and QueryString properties.

    Response Object

    The Response object represents the server's response to the client request. It is an instance of the System.Web.HttpResponse class.

    In ASP.NET, the response object does not play any vital role in sending HTML text to the client, because the server-side controls have nested, object oriented methods for rendering themselves.

    However, the HttpResponse object still provides some important functionalities, like the cookie feature and the Redirect() method. The Response.Redirect() method allows transferring the user to another page, inside as well as outside the application. It requires a round trip.

    Properties and Methods of the Response Object

    The following table provides some noteworthy properties of the Response object:

    PropertyDescription
    BufferGets or sets a value indicating whether to buffer the output and send it after the complete response is finished processing.
    BufferOutputGets or sets a value indicating whether to buffer the output and send it after the complete page is finished processing.
    CharsetGets or sets the HTTP character set of the output stream.
    ContentEncodingGets or sets the HTTP character set of the output stream.
    ContentTypeGets or sets the HTTP MIME type of the output stream.
    CookiesGets the response cookie collection.
    ExpiresGets or sets the number of minutes before a page cached on a browser expires.
    ExpiresAbsoluteGets or sets the absolute date and time at which to remove cached information from the cache.
    HeaderEncodingGets or sets an encoding object that represents the encoding for the current header output stream.
    HeadersGets the collection of response headers.
    IsClientConnectedGets a value indicating whether the client is still connected to the server.
    OutputEnables output of text to the outgoing HTTP response stream.
    OutputStreamEnables binary output to the outgoing HTTP content body.
    RedirectLocationGets or sets the value of the Http Location header.
    StatusSets the status line that is returned to the client.
    StatusCodeGets or sets the HTTP status code of the output returned to the client.
    StatusDescriptionGets or sets the HTTP status string of the output returned to the client.
    SubStatusCodeGets or sets a value qualifying the status code of the response.
    SuppressContentGets or sets a value indicating whether to send HTTP content to the client.

    The following table provides a list of some important methods:

    MethodDescription
    AddHeaderAdds an HTTP header to the output stream. AddHeader is provided for compatibility with earlier versions of ASP.
    AppendCookieInfrastructure adds an HTTP cookie to the intrinsic cookie collection.
    AppendHeaderAdds an HTTP header to the output stream.
    AppendToLogAdds custom log information to the InterNET Information Services (IIS) log file.
    BinaryWriteWrites a string of binary characters to the HTTP output stream.
    ClearContentClears all content output from the buffer stream.
    CloseCloses the socket connection to a client.
    EndSends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.
    Equals(Object)Determines whether the specified object is equal to the current object.
    FlushSends all currently buffered output to the client.
    GetTypeGets the Type of the current instance.
    PicsAppends a HTTP PICS-Label header to the output stream.
    Redirect(String)Redirects a request to a new URL and specifies the new URL.
    Redirect(String, Boolean)Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.
    SetCookieUpdates an existing cookie in the cookie collection.
    ToStringReturns a String that represents the current Object.
    TransmitFile(String)Writes the specified file directly to an HTTP response output stream, without buffering it in memory.
    Write(Char)Writes a character to an HTTP response output stream.
    Write(Object)Writes an object to an HTTP response stream.
    Write(String)Writes a string to an HTTP response output stream.
    WriteFile(String)Writes the contents of the specified file directly to an HTTP response output stream as a file block.
    WriteFile(String, Boolean)Writes the contents of the specified file directly to an HTTP response output stream as a memory block.

    Example

    The following simple example has a text box control where the user can enter name, a button to send the information to the server, and a label control to display the URL of the client computer.

    The content file:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
       Inherits="server_side._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    
       <head runat="server">
          <title>Untitled Page</title>
       </head>
       
       <body>
          <form id="form1" runat="server">
             <div>
                
                Enter your name:
                <br />
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
                <br />
                <asp:Label ID="Label1" runat="server"/>
    
             </div>
          </form>
       </body>
       
    </html>

    The code behind Button1_Click:

    protected void Button1_Click(object sender, EventArgs e) {
    
       if (!String.IsNullOrEmpty(TextBox1.Text)) {
       
          // Access the HttpServerUtility methods through
          // the intrinsic Server object.
          Label1.Text = "Welcome, " + Server.HtmlEncode(TextBox1.Text) + ". <br/> The url is " + Server.UrlEncode(Request.Url.ToString())
       }
    }

    Run the page to see the following result:

    ASP.NET Server Side

    HTML Server

     The HTML server controls are basically the standard HTML controls enhanced to enable server side processing. The HTML controls such as the header tags, anchor tags, and input elements are not processed by the server but are sent to the browser for display.

    They are specifically converted to a server control by adding the attribute runat="server" and adding an id attribute to make them available for server-side processing.

    For example, consider the HTML input control:

    <input type="text" size="40">

    It could be converted to a server control, by adding the runat and id attribute:

    <input type="text" id="testtext" size="40" runat="server">

    Advantages of using HTML Server Controls

    Although ASP.NET server controls can perform every job accomplished by the HTML server controls, the later controls are useful in the following cases:

    • Using static tables for layout purposes.
    • Converting a HTML page to run under ASP.NET

    The following table describes the HTML server controls:

    Control NameHTML tag
    HtmlHead<head>element
    HtmlInputButton<input type=button|submit|reset>
    HtmlInputCheckbox<input type=checkbox>
    HtmlInputFile<input type = file>
    HtmlInputHidden<input type = hidden>
    HtmlInputImage<input type = image>
    HtmlInputPassword<input type = password>
    HtmlInputRadioButton<input type = radio>
    HtmlInputReset<input type = reset>
    HtmlText<input type = text|password>
    HtmlImage<img> element
    HtmlLink<link> element
    HtmlAnchor<a> element
    HtmlButton<button> element
    HtmlButton<button> element
    HtmlForm<form> element
    HtmlTable<table> element
    HtmlTableCell<td> and <th>
    HtmlTableRow<tr> element
    HtmlTitle<title> element
    HtmlSelect<select&t; element
    HtmlGenericControlAll HTML controls not listed

    Example

    The following example uses a basic HTML table for layout. It uses some boxes for getting input from the users such as name, address, city, state etc. It also has a button control, which is clicked to get the user data displayed in the last row of the table.

    The page should look like this in the design view:

    ASP.NET Server Controls

    The code for the content page shows the use of the HTML table element for layout.

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="htmlserver._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    
       <head runat="server">
          <title>Untitled Page</title>
          
          <style type="text/css">
             .style1
             {  
                width: 156px;
             }
             .style2
             {
                width: 332px;
             }
          </style>
          
       </head>
       
       <body>
          <form id="form1" runat="server">
             <div>
                <table style="width: 54%;">
                   <tr>
                      <td class="style1">Name:</td>
                      <td class="style2">
                         <asp:TextBox ID="txtname" runat="server"  style="width:230px">
                         </asp:TextBox>
                      </td>
                   </tr>
    				
                   <tr>
                      <td class="style1">Street</td>
                      <td class="style2">
                         <asp:TextBox ID="txtstreet" runat="server"  style="width:230px">
                         </asp:TextBox>
                      </td>
                   </tr>
    				
                   <tr>
                      <td class="style1">City</td>
                      <td class="style2">
                         <asp:TextBox ID="txtcity" runat="server"  style="width:230px">
                         </asp:TextBox>
                      </td>
                   </tr>
    				
                   <tr>
                      <td class="style1">State</td>
                      <td class="style2">
                         <asp:TextBox ID="txtstate" runat="server" style="width:230px">
                         </asp:TextBox>
                      </td>
                   </tr>
    				
                   <tr>
                      <td class="style1"> </td>
                      <td class="style2"></td>
                   </tr>
    				
                   <tr>
                      <td class="style1"></td>
                      <td ID="displayrow" runat ="server" class="style2">
                      </td>
                   </tr>
                </table>
                
             </div>
             <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" />
          </form>
       </body>
    </html>

    The code behind the button control:

    protected void Button1_Click(object sender, EventArgs e)
    {
       string str = "";
       str += txtname.Text + "<br />";
       str += txtstreet.Text + "<br />";
       str += txtcity.Text + "<br />";
       str += txtstate.Text + "<br />";
       displayrow.InnerHtml = str;
    }

    Observe the following:

    • The standard HTML tags have been used for the page layout.

    • The last row of the HTML table is used for data display. It needed server side processing, so an ID attribute and the runat attribute has been added to it.

    Client Side

    ASP.NET client side coding has two aspects:

    • Client side scripts : It runs on the browser and in turn speeds up the execution of page. For example, client side data validation which can catch invalid data and warn the user accordingly without making a round trip to the server.

    • Client side source code : ASP.NET pages generate this. For example, the HTML source code of an ASP.NET page contains a number of hidden fields and automatically injected blocks of JavaScript code, which keeps information like view state or does other jobs to make the page work.

    Client Side Scripts

    All ASP.NET server controls allow calling client side code written using JavaScript or VBScript. Some ASP.NET server controls use client side scripting to provide response to the users without posting back to the server. For example, the validation controls.

    Apart from these scripts, the Button control has a property OnClientClick, which allows executing client-side script, when the button is clicked.

    The traditional and server HTML controls have the following events that can execute a script when they are raised:

    EventDescription
    onblurWhen the control loses focus
    onfocusWhen the control receives focus
    onclickWhen the control is clicked
    onchangeWhen the value of the control changes
    onkeydownWhen the user presses a key
    onkeypressWhen the user presses an alphanumeric key
    onkeyupWhen the user releases a key
    onmouseoverWhen the user moves the mouse pointer over the control
    onserverclickIt raises the ServerClick event of the control, when the control is clicked

    Client Side Source Code

    We have already discussed that, ASP.NET pages are generally written in two files:

    • The content file or the markup file ( .aspx)
    • The code-behind file

    The content file contains the HTML or ASP.NET control tags and literals to form the structure of the page. The code behind file contains the class definition. At run-time, the content file is parsed and transformed into a page class.

    This class, along with the class definition in the code file, and system generated code, together make the executable code (assembly) that processes all posted data, generates response, and sends it back to the client.

    Consider the simple page:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
       Inherits="clientside._Default" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    
       <head runat="server">
          <title>
             Untitled Page
          </title>
       </head>
       
       <body>
          <form id="form1" runat="server">
          
             <div>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Click" />
             </div>
             
             <hr />
             
             <h3> <asp:Label ID="Msg" runat="server" Text=""> </asp:Label> </h3>
          </form>
       </body>
       
    </html>

    When this page is run on the browser, the View Source option shows the HTML page sent to the browser by the ASP.Net runtime:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html xmlns="http://www.w3.org/1999/xhtml" >
    
       <head>
          <title>
             Untitled Page
          </title>
       </head>
       
       <body>
          <form name="form1" method="post" action="Default.aspx" id="form1">
          
             <div>
                <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
                   value="/wEPDwUKMTU5MTA2ODYwOWRk31NudGDgvhhA7joJum9Qn5RxU2M=" />
             </div>
     
             <div>
                <input type="hidden" name="__EVENTVALIDATION"  id="__EVENTVALIDATION" 
                   value="/wEWAwKpjZj0DALs0bLrBgKM54rGBhHsyM61rraxE+KnBTCS8cd1QDJ/"/>
             </div>
    
             <div>
                <input name="TextBox1" type="text" id="TextBox1" />  
                <input type="submit" name="Button1" value="Click" id="Button1" />
             </div>
    
             <hr />
             <h3><span id="Msg"></span></h3>
             
          </form>
       </body>
    </html>

    If you go through the code properly, you can see that first two <div> tags contain the hidden fields which store the view state and validation information.

    Basic Controls

    In this chapter, we will discuss the basic controls available in ASP.NET.

    Button Controls

    ASP.NET provides three types of button control:

    • Button : It displays text within a rectangular area.

    • Link Button : It displays text that looks like a hyperlink.

    • Image Button : It displays an image.

    When a user clicks a button, two events are raised: Click and Command.

    Basic syntax of button control:

    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" / >

    Common properties of the button control:

    PropertyDescription
    TextThe text displayed on the button. This is for button and link button controls only.
    ImageUrlFor image button control only. The image to be displayed for the button.
    AlternateTextFor image button control only. The text to be displayed if the browser cannot display the image.
    CausesValidationDetermines whether page validation occurs when a user clicks the button. The default is true.
    CommandNameA string value that is passed to the command event when a user clicks the button.
    CommandArgumentA string value that is passed to the command event when a user clicks the button.
    PostBackUrlThe URL of the page that is requested when the user clicks the button.

    Text Boxes and Labels

    Text box controls are typically used to accept input from the user. A text box control can accept one or more lines of text depending upon the settings of the TextMode attribute.

    Label controls provide an easy way to display text which can be changed from one execution of a page to the next. If you want to display text that does not change, you use the literal text.

    Basic syntax of text control:

    <asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>

    Common Properties of the Text Box and Labels:

    PropertyDescription
    TextModeSpecifies the type of text box. SingleLine creates a standard text box, MultiLIne creates a text box that accepts more than one line of text and the Password causes the characters that are entered to be masked. The default is SingleLine.
    TextThe text content of the text box.
    MaxLengthThe maximum number of characters that can be entered into the text box.
    WrapIt determines whether or not text wraps automatically for multi-line text box; default is true.
    ReadOnlyDetermines whether the user can change the text in the box; default is false, i.e., the user can not change the text.
    ColumnsThe width of the text box in characters. The actual width is determined based on the font that is used for the text entry.
    RowsThe height of a multi-line text box in lines. The default value is 0, means a single line text box.

    The mostly used attribute for a label control is 'Text', which implies the text displayed on the label.

    Check Boxes and Radio Buttons

    A check box displays a single option that the user can either check or uncheck and radio buttons present a group of options from which the user can select just one option.

    To create a group of radio buttons, you specify the same name for the GroupName attribute of each radio button in the group. If more than one group is required in a single form, then specify a different group name for each group.

    If you want check box or radio button to be selected when the form is initially displayed, set its Checked attribute to true. If the Checked attribute is set to true for multiple radio buttons in a group, then only the last one is considered as true.

    Basic syntax of check box:

    <asp:CheckBox ID= "chkoption" runat= "Server"> 
    </asp:CheckBox>

    Basic syntax of radio button:

    <asp:RadioButton ID= "rdboption" runat= "Server"> 
    </asp: RadioButton>

    Common properties of check boxes and radio buttons:

    PropertyDescription
    TextThe text displayed next to the check box or radio button.
    CheckedSpecifies whether it is selected or not, default is false.
    GroupNameName of the group the control belongs to.

    List Controls

    ASP.NET provides the following controls

    • Drop-down list,
    • List box,
    • Radio button list,
    • Check box list,
    • Bulleted list.

    These control let a user choose from one or more items from the list. List boxes and drop-down lists contain one or more list items. These lists can be loaded either by code or by the ListItemCollection editor.

    Basic syntax of list box control:

    <asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"    OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
    </asp:ListBox>

    Basic syntax of drop-down list control:

    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"   OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    </asp:DropDownList>

    Common properties of list box and drop-down Lists:

    PropertyDescription
    ItemsThe collection of ListItem objects that represents the items in the control. This property returns an object of type ListItemCollection.
    RowsSpecifies the number of items displayed in the box. If actual list contains more rows than displayed then a scroll bar is added.
    SelectedIndexThe index of the currently selected item. If more than one item is selected, then the index of the first selected item. If no item is selected, the value of this property is -1.
    SelectedValueThe value of the currently selected item. If more than one item is selected, then the value of the first selected item. If no item is selected, the value of this property is an empty string ("").
    SelectionModeIndicates whether a list box allows single selections or multiple selections.

    Common properties of each list item objects:

    PropertyDescription
    TextThe text displayed for the item.
    SelectedIndicates whether the item is selected.
    ValueA string value associated with the item.

    It is important to notes that:

    • To work with the items in a drop-down list or list box, you use the Items property of the control. This property returns a ListItemCollection object which contains all the items of the list.

    • The SelectedIndexChanged event is raised when the user selects a different item from a drop-down list or list box.

    The ListItemCollection

    The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents one item in the list. Items in a ListItemCollection are numbered from 0.

    When the items into a list box are loaded using strings like: lstcolor.Items.Add("Blue"), then both the Text and Value properties of the list item are set to the string value you specify. To set it differently you must create a list item object and then add that item to the collection.

    The ListItemCollection Editor is used to add item to a drop-down list or list box. This is used to create a static list of items. To display the collection editor, select edit item from the smart tag menu, or select the control and then click the ellipsis button from the Item property in the properties window.

    Common properties of ListItemCollection:

    PropertyDescription
    Item(integer)A ListItem object that represents the item at the specified index.
    CountThe number of items in the collection.

    Common methods of ListItemCollection:

    MethodsDescription
    Add(string)Adds a new item at the end of the collection and assigns the string parameter to the Text property of the item.
    Add(ListItem)Adds a new item at the end of the collection.
    Insert(integer, string)Inserts an item at the specified index location in the collection, and assigns string parameter to the text property of the item.
    Insert(integer, ListItem)Inserts the item at the specified index location in the collection.
    Remove(string)Removes the item with the text value same as the string.
    Remove(ListItem)Removes the specified item.
    RemoveAt(integer)Removes the item at the specified index as the integer.
    ClearRemoves all the items of the collection.
    FindByValue(string)Returns the item whose value is same as the string.
    FindByValue(Text)Returns the item whose text is same as the string.

    Radio Button list and Check Box list

    A radio button list presents a list of mutually exclusive options. A check box list presents a list of independent options. These controls contain a collection of ListItem objects that could be referred to through the Items property of the control.

    Basic syntax of radio button list:

    <asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True" 
       OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
    </asp:RadioButtonList>

    Basic syntax of check box list:

    <asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True" 
       OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
    </asp:CheckBoxList>

    Common properties of check box and radio button lists:

    PropertyDescription
    RepeatLayoutThis attribute specifies whether the table tags or the normal html flow to use while formatting the list when it is rendered. The default is Table.
    RepeatDirectionIt specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical.
    RepeatColumnsIt specifies the number of columns to use when repeating the controls; default is 0.

    Bulleted lists and Numbered lists

    The bulleted list control creates bulleted lists or numbered lists. These controls contain a collection of ListItem objects that could be referred to through the Items property of the control.

    Basic syntax of a bulleted list:

    <asp:BulletedList ID="BulletedList1" runat="server">
    </asp:BulletedList>

    Common properties of the bulleted list:

    PropertyDescription
    BulletStyleThis property specifies the style and looks of the bullets, or numbers.
    RepeatDirectionIt specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical.
    RepeatColumnsIt specifies the number of columns to use when repeating the controls; default is 0.

    HyperLink Control

    The HyperLink control is like the HTML <a> element.

    Basic syntax for a hyperlink control:

    <asp:HyperLink ID="HyperLink1" runat="server">
       HyperLink
    </asp:HyperLink>

    It has the following important properties:

    PropertyDescription
    ImageUrlPath of the image to be displayed by the control.
    NavigateUrlTarget link URL.
    TextThe text to be displayed as the link.
    TargetThe window or frame which loads the linked page.

    Image Control

    The image control is used for displaying images on the web page, or some alternative text, if the image is not available.

    Basic syntax for an image control:

    <asp:Image ID="Image1" runat="server">

    It has the following important properties:

    PropertyDescription
    AlternateTextAlternate text to be displayed in absence of the image.
    ImageAlignAlignment options for the control.
    ImageUrlPath of the image to be displayed by the control.

    Directives

    ASP.NET directives are instructions to specify optional settings, such as registering a custom control and page language. These settings describe how the web forms (.aspx) or user controls (.ascx) pages are processed by the .Net framework.

    The syntax for declaring a directive is:

    <%@  directive_name attribute=value  [attribute=value]  %>

    In this section, we will just introduce the ASP.NET directives and we will use most of these directives throughout the tutorials.

    The Application Directive

    The Application directive defines application-specific attributes. It is provided at the top of the global.aspx file.

    The basic syntax of Application directive is:

    <%@ Application Language="C#" %>

    The attributes of the Application directive are:

    AttributesDescription
    InheritsThe name of the class from which to inherit.
    DescriptionThe text description of the application. Parsers and compilers ignore this.
    LanguageThe language used in code blocks.

    The Assembly Directive

    The Assembly directive links an assembly to the page or the application at parse time. This could appear either in the global.asax file for application-wide linking, in the page file, a user control file for linking to a page or user control.

    The basic syntax of Assembly directive is:

    <%@ Assembly Name ="myassembly" %>

    The attributes of the Assembly directive are:

    AttributesDescription
    NameThe name of the assembly to be linked.
    SrcThe path to the source file to be linked and compiled dynamically.

    The Control Directive

    The control directive is used with the user controls and appears in the user control (.ascx) files.

    The basic syntax of Control directive is:

    <%@ Control Language="C#"  EnableViewState="false" %>

    The attributes of the Control directive are:

    AttributesDescription
    AutoEventWireupThe Boolean value that enables or disables automatic association of events to handlers.
    ClassNameThe file name for the control.
    DebugThe Boolean value that enables or disables compiling with debug symbols.
    DescriptionThe text description of the control page, ignored by compiler.
    EnableViewStateThe Boolean value that indicates whether view state is maintained across page requests.
    ExplicitFor VB language, tells the compiler to use option explicit mode.
    InheritsThe class from which the control page inherits.
    LanguageThe language for code and script.
    SrcThe filename for the code-behind class.
    StrictFor VB language, tells the compiler to use the option strict mode.

    The Implements Directive

    The Implement directive indicates that the web page, master page or user control page must implement the specified .Net framework interface.

    The basic syntax for implements directive is:

    <%@ Implements  Interface="interface_name" %>

    The Import Directive

    The Import directive imports a namespace into a web page, user control page of application. If the Import directive is specified in the global.asax file, then it is applied to the entire application. If it is in a page of user control page, then it is applied to that page or control.

    The basic syntax for import directive is:

    <%@ namespace="System.Drawing" %>

    The Master Directive

    The Master directive specifies a page file as being the mater page.

    The basic syntax of sample MasterPage directive is:

    <%@ MasterPage Language="C#"  AutoEventWireup="true"  CodeFile="SiteMater.master.cs" Inherits="SiteMaster"  %>

    The MasterType Directive

    The MasterType directive assigns a class name to the Master property of a page, to make it strongly typed.

    The basic syntax of MasterType directive is:

    <%@ MasterType attribute="value"[attribute="value" ...]  %>

    The OutputCache Directive

    The OutputCache directive controls the output caching policies of a web page or a user control.

    The basic syntax of OutputCache directive is:

    <%@ OutputCache Duration="15" VaryByParam="None"  %>

    The Page Directive

    The Page directive defines the attributes specific to the page file for the page parser and the compiler.

    The basic syntax of Page directive is:

    <%@ Page Language="C#"  AutoEventWireup="true" CodeFile="Default.aspx.cs"  Inherits="_Default"  Trace="true" %>

    The attributes of the Page directive are:

    AttributesDescription
    AutoEventWireupThe Boolean value that enables or disables page events that are being automatically bound to methods; for example, Page_Load.
    BufferThe Boolean value that enables or disables HTTP response buffering.
    ClassNameThe class name for the page.
    ClientTargetThe browser for which the server controls should render content.
    CodeFileThe name of the code behind file.
    DebugThe Boolean value that enables or disables compilation with debug symbols.
    DescriptionThe text description of the page, ignored by the parser.
    EnableSessionStateIt enables, disables, or makes session state read-only.
    EnableViewStateThe Boolean value that enables or disables view state across page requests.
    ErrorPageURL for redirection if an unhandled page exception occurs.
    InheritsThe name of the code behind or other class.
    LanguageThe programming language for code.
    SrcThe file name of the code behind class.
    TraceIt enables or disables tracing.
    TraceModeIt indicates how trace messages are displayed, and sorted by time or category.
    TransactionIt indicates if transactions are supported.
    ValidateRequestThe Boolean value that indicates whether all input data is validated against a hardcoded list of values.

    The PreviousPageType Directive

    The PreviousPageType directive assigns a class to a page, so that the page is strongly typed.

    The basic syntax for a sample PreviousPagetype directive is:

    <%@ PreviousPageType attribute="value"[attribute="value" ...]   %>

    The Reference Directive

    The Reference directive indicates that another page or user control should be compiled and linked to the current page.

    The basic syntax of Reference directive is:

    <%@ Reference Page ="somepage.aspx" %>

    The Register Directive

    The Register derivative is used for registering the custom server controls and user controls.

    The basic syntax of Register directive is:

    <%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>
    Categories:
    Similar Videos

    0 Comments: