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:
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:
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:
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:
Event | Attribute | Controls |
---|---|---|
Click | OnClick | Button, image button, link button, image map |
Command | OnCommand | Button, image button, link button |
TextChanged | OnTextChanged | Text box |
SelectedIndexChanged | OnSelectedIndexChanged | Drop-down list, list box, radio button list, check box list. |
CheckedChanged | OnCheckedChanged | Check 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:
Control | Default Event |
---|---|
AdRotator | AdCreated |
BulletedList | Click |
Button | Click |
Calender | SelectionChanged |
CheckBox | CheckedChanged |
CheckBoxList | SelectedIndexChanged |
DataGrid | SelectedIndexChanged |
DataList | SelectedIndexChanged |
DropDownList | SelectedIndexChanged |
HyperLink | Click |
ImageButton | Click |
ImageMap | Click |
LinkButton | Click |
ListBox | SelectedIndexChanged |
Menu | MenuItemClick |
RadioButton | CheckedChanged |
RadioButtonList | SelectedIndexChanged |
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:
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:
Property | Description |
---|---|
MachineName | Name of server computer |
ScriptTimeOut | Gets and sets the request time-out value in seconds. |
The following table provides a list of some important methods:
Method | Description |
---|---|
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. |
GetLastError | Returns the previous exception. |
GetType | Gets the Type of the current instance. |
HtmlEncode | Changes an ordinary string into a string with legal HTML characters. |
HtmlDecode | Converts an Html string into an ordinary string. |
ToString | Returns 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. |
UrlDecode | Converts an URL string into an ordinary string. |
UrlEncodeToken | Works same as UrlEncode, but on a byte array that contains Base64-encoded data. |
UrlDecodeToken | Works same as UrlDecode, but on a byte array that contains Base64-encoded data. |
MapPath | Return the physical path that corresponds to a specified virtual file path on the server. |
Transfer | Transfers 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:
Property | Description |
---|---|
AcceptTypes | Gets a string array of client-supported MIME accept types. |
ApplicationPath | Gets the ASP.NET application's virtual application root path on the server. |
Browser | Gets or sets information about the requesting client's browser capabilities. |
ContentEncoding | Gets or sets the character set of the entity-body. |
ContentLength | Specifies the length, in bytes, of content sent by the client. |
ContentType | Gets or sets the MIME content type of the incoming request. |
Cookies | Gets a collection of cookies sent by the client. |
FilePath | Gets the virtual path of the current request. |
Files | Gets the collection of files uploaded by the client, in multipart MIME format. |
Form | Gets a collection of form variables. |
Headers | Gets a collection of HTTP headers. |
HttpMethod | Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client. |
InputStream | Gets the contents of the incoming HTTP entity body. |
IsSecureConnection | Gets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS). |
QueryString | Gets the collection of HTTP query string variables. |
RawUrl | Gets the raw URL of the current request. |
RequestType | Gets or sets the HTTP data transfer method (GET or POST) used by the client. |
ServerVariables | Gets a collection of Web server variables. |
TotalBytes | Gets the number of bytes in the current input stream. |
Url | Gets information about the URL of the current request. |
UrlReferrer | Gets information about the URL of the client's previous request that is linked to the current URL. |
UserAgent | Gets the raw user agent string of the client browser. |
UserHostAddress | Gets the IP host address of the remote client. |
UserHostName | Gets the DNS name of the remote client. |
UserLanguages | Gets a sorted string array of client language preferences. |
The following table provides a list of some important methods:
Method | Description |
---|---|
BinaryRead | Performs 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.) |
GetType | Gets the Type of the current instance. |
MapImageCoordinates | Maps 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. |
SaveAs | Saves an HTTP request to disk. |
ToString | Returns a String that represents the current object. |
ValidateInput | Causes 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:
Property | Description |
---|---|
Buffer | Gets or sets a value indicating whether to buffer the output and send it after the complete response is finished processing. |
BufferOutput | Gets or sets a value indicating whether to buffer the output and send it after the complete page is finished processing. |
Charset | Gets or sets the HTTP character set of the output stream. |
ContentEncoding | Gets or sets the HTTP character set of the output stream. |
ContentType | Gets or sets the HTTP MIME type of the output stream. |
Cookies | Gets the response cookie collection. |
Expires | Gets or sets the number of minutes before a page cached on a browser expires. |
ExpiresAbsolute | Gets or sets the absolute date and time at which to remove cached information from the cache. |
HeaderEncoding | Gets or sets an encoding object that represents the encoding for the current header output stream. |
Headers | Gets the collection of response headers. |
IsClientConnected | Gets a value indicating whether the client is still connected to the server. |
Output | Enables output of text to the outgoing HTTP response stream. |
OutputStream | Enables binary output to the outgoing HTTP content body. |
RedirectLocation | Gets or sets the value of the Http Location header. |
Status | Sets the status line that is returned to the client. |
StatusCode | Gets or sets the HTTP status code of the output returned to the client. |
StatusDescription | Gets or sets the HTTP status string of the output returned to the client. |
SubStatusCode | Gets or sets a value qualifying the status code of the response. |
SuppressContent | Gets or sets a value indicating whether to send HTTP content to the client. |
The following table provides a list of some important methods:
Method | Description |
---|---|
AddHeader | Adds an HTTP header to the output stream. AddHeader is provided for compatibility with earlier versions of ASP. |
AppendCookie | Infrastructure adds an HTTP cookie to the intrinsic cookie collection. |
AppendHeader | Adds an HTTP header to the output stream. |
AppendToLog | Adds custom log information to the InterNET Information Services (IIS) log file. |
BinaryWrite | Writes a string of binary characters to the HTTP output stream. |
ClearContent | Clears all content output from the buffer stream. |
Close | Closes the socket connection to a client. |
End | Sends 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. |
Flush | Sends all currently buffered output to the client. |
GetType | Gets the Type of the current instance. |
Pics | Appends 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. |
SetCookie | Updates an existing cookie in the cookie collection. |
ToString | Returns 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:
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 Name | HTML 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 |
HtmlGenericControl | All 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:
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:
Event | Description |
---|---|
onblur | When the control loses focus |
onfocus | When the control receives focus |
onclick | When the control is clicked |
onchange | When the value of the control changes |
onkeydown | When the user presses a key |
onkeypress | When the user presses an alphanumeric key |
onkeyup | When the user releases a key |
onmouseover | When the user moves the mouse pointer over the control |
onserverclick | It 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:
Property | Description |
---|---|
Text | The text displayed on the button. This is for button and link button controls only. |
ImageUrl | For image button control only. The image to be displayed for the button. |
AlternateText | For image button control only. The text to be displayed if the browser cannot display the image. |
CausesValidation | Determines whether page validation occurs when a user clicks the button. The default is true. |
CommandName | A string value that is passed to the command event when a user clicks the button. |
CommandArgument | A string value that is passed to the command event when a user clicks the button. |
PostBackUrl | The 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:
Property | Description |
---|---|
TextMode | Specifies 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. |
Text | The text content of the text box. |
MaxLength | The maximum number of characters that can be entered into the text box. |
Wrap | It determines whether or not text wraps automatically for multi-line text box; default is true. |
ReadOnly | Determines whether the user can change the text in the box; default is false, i.e., the user can not change the text. |
Columns | The width of the text box in characters. The actual width is determined based on the font that is used for the text entry. |
Rows | The 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:
Property | Description |
---|---|
Text | The text displayed next to the check box or radio button. |
Checked | Specifies whether it is selected or not, default is false. |
GroupName | Name 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:
Property | Description |
---|---|
Items | The collection of ListItem objects that represents the items in the control. This property returns an object of type ListItemCollection. |
Rows | Specifies the number of items displayed in the box. If actual list contains more rows than displayed then a scroll bar is added. |
SelectedIndex | The 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. |
SelectedValue | The 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 (""). |
SelectionMode | Indicates whether a list box allows single selections or multiple selections. |
Common properties of each list item objects:
Property | Description |
---|---|
Text | The text displayed for the item. |
Selected | Indicates whether the item is selected. |
Value | A 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:
Property | Description |
---|---|
Item(integer) | A ListItem object that represents the item at the specified index. |
Count | The number of items in the collection. |
Common methods of ListItemCollection:
Methods | Description |
---|---|
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. |
Clear | Removes 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:
Property | Description |
---|---|
RepeatLayout | This 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. |
RepeatDirection | It specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical. |
RepeatColumns | It 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:
Property | Description |
---|---|
BulletStyle | This property specifies the style and looks of the bullets, or numbers. |
RepeatDirection | It specifies the direction in which the controls to be repeated. The values available are Horizontal and Vertical. Default is Vertical. |
RepeatColumns | It 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:
Property | Description |
---|---|
ImageUrl | Path of the image to be displayed by the control. |
NavigateUrl | Target link URL. |
Text | The text to be displayed as the link. |
Target | The 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:
Property | Description |
---|---|
AlternateText | Alternate text to be displayed in absence of the image. |
ImageAlign | Alignment options for the control. |
ImageUrl | Path 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:
Attributes | Description |
---|---|
Inherits | The name of the class from which to inherit. |
Description | The text description of the application. Parsers and compilers ignore this. |
Language | The 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:
Attributes | Description |
---|---|
Name | The name of the assembly to be linked. |
Src | The 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:
Attributes | Description |
---|---|
AutoEventWireup | The Boolean value that enables or disables automatic association of events to handlers. |
ClassName | The file name for the control. |
Debug | The Boolean value that enables or disables compiling with debug symbols. |
Description | The text description of the control page, ignored by compiler. |
EnableViewState | The Boolean value that indicates whether view state is maintained across page requests. |
Explicit | For VB language, tells the compiler to use option explicit mode. |
Inherits | The class from which the control page inherits. |
Language | The language for code and script. |
Src | The filename for the code-behind class. |
Strict | For 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:
Attributes | Description |
---|---|
AutoEventWireup | The Boolean value that enables or disables page events that are being automatically bound to methods; for example, Page_Load. |
Buffer | The Boolean value that enables or disables HTTP response buffering. |
ClassName | The class name for the page. |
ClientTarget | The browser for which the server controls should render content. |
CodeFile | The name of the code behind file. |
Debug | The Boolean value that enables or disables compilation with debug symbols. |
Description | The text description of the page, ignored by the parser. |
EnableSessionState | It enables, disables, or makes session state read-only. |
EnableViewState | The Boolean value that enables or disables view state across page requests. |
ErrorPage | URL for redirection if an unhandled page exception occurs. |
Inherits | The name of the code behind or other class. |
Language | The programming language for code. |
Src | The file name of the code behind class. |
Trace | It enables or disables tracing. |
TraceMode | It indicates how trace messages are displayed, and sorted by time or category. |
Transaction | It indicates if transactions are supported. |
ValidateRequest | The 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" %>
0 Comments: