ASP.Net
ASP.Net
NET - Introduction
It allows you to use a full featured programming language such as C# or VB.NET to build web
applications easily.
C#
Visual Basic.Net
Jscript
J#
ASP.NET is used to produce interactive, data-driven web applications over the internet. It
consists of a large number of controls such as text boxes, buttons, and labels for assembling,
configuring, and manipulating code to create HTML pages.
ASP.NET Web Forms Model
ASP.NET web forms extend the event-driven model of interaction to the web applications. The
browser submits a web form to the web server and the server returns a full markup page or
HTML page in response.
All client side user activities are forwarded to the server for stateful processing. The server
processes the output of the client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.NET framework helps in storing the information
regarding the state of the application, which consists of:
Page state
Session state
The page state is the state of the client, i.e., the content of various input fields in the web form.
The session state is the collective information obtained from various pages the user visited and
worked with, i.e., the overall session state. To clear the concept, let us take an example of a
shopping cart.
User adds items to a shopping cart. Items are selected from a page, say the items page, and the
total collected items and price are shown on a different page, say the cart page. Only HTTP
cannot keep track of all the information coming from various pages. ASP.NET session state and
server side infrastructure keeps track of the information collected globally over a session.
The ASP.NET runtime carries the page state to and from the server across page requests while
generating ASP.NET runtime codes, and incorporates the state of the server side components in
hidden fields.
This way, the server becomes aware of the overall application state and operates in a two-tiered
connected way.
The ASP.NET Component Model
The ASP.NET component model provides various building blocks of ASP.NET pages. Basically
it is an object model, which describes:
Server side counterparts of almost all HTML elements or tags, such as <form> and <input>.
Server controls, which help in developing complex user-interface. For example, the Calendar
control or the Gridview control.
ASP.NET is a technology, which works on the .Net framework that contains all web-related
functionalities. The .Net framework is made of an object-oriented hierarchy. An ASP.NET web
application is made of pages. When a user requests an ASP.NET page, the IIS delegates the
processing of the page to the ASP.NET runtime system.
The ASP.NET runtime transforms the .aspx page into an instance of a class, which inherits from
the base class page of the .Net framework. Therefore, each ASP.NET page is an object and all its
components i.e., the server-side controls are also objects.
Components of .Net Framework
The following table describes the components of the .Net framework and the job they perform:
Components and their Description
(1) Common Language Runtime or CLR
It performs memory management, exception handling, debugging, security checking, thread
execution, code execution, code safety, verification, and compilation. The code that is directly
managed by the CLR is called the managed code. When the managed code is compiled, the
compiler converts the source code into a CPU independent intermediate language (IL) code. A
Just In Time(JIT) compiler compiles the IL code into native code, which is CPU specific.
(2) .Net Framework Class Library
It contains a huge library of reusable types. classes, interfaces, structures, and enumerated values,
which are collectively called types.
(3) Common Language Specification
It contains the specifications for the .Net supported languages and implementation of language
integration.
(4) Common Type System
It provides guidelines for declaring, using, and managing types at runtime, and cross-language
communication.
(5) Metadata and Assemblies
Metadata is the binary information describing the program, which is either stored in a portable
executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly
manifest, type metadata, IL code, and a set of resources like image files.
(6) Windows Forms
Windows Forms contain the graphical representation of any window displayed in the application.
(7) ASP.NET and ASP.NET AJAX
ASP.NET is the web development model and AJAX is an extension of ASP.NET for developing
and implementing AJAX functionality. ASP.NET AJAX contains the components that allow the
developer to update data on a website without a complete reload of the page.
(8) ADO.NET
It is the technology used for working with data and databases. It provides access to data sources
like SQL server, OLE DB, XML etc. The ADO.NET allows connection to data sources for
retrieving, manipulating, and updating data.
(9) Windows Workflow Foundation (WF)
It helps in building workflow-based applications in Windows. It contains activities, workflow
runtime, workflow designer, and a rules engine.
(10) Windows Presentation Foundation
It provides a separation between the user interface and the business logic. It helps in developing
visually stunning interfaces using documents, media, two and three dimensional graphics,
animations, and more.
(11) Windows Communication Foundation (WCF)
It is the technology used for building and executing connected systems.
(12) Windows CardSpace
It provides safety for accessing resources and sharing personal information on the internet.
(13) LINQ
It imparts data querying capabilities to .Net languages using a syntax which is similar to the
tradition query language SQL.
ASP.NET - Environment Setup
ASP.NET provides an abstraction layer on top of HTTP on which the web applications are built.
It provides high-level entities such as classes and components within an object-oriented
paradigm.
The key development tool for building ASP.NET applications and front ends is Visual Studio.
Visual Studio is an integrated development environment for writing, compiling, and debugging
the code. It provides a complete set of development tools for building ASP.NET web
applications, web services, desktop applications, and mobile applications.
Installation
Microsoft provides a free version of visual studio which also contains SQL Server and it can be
downloaded from www.visualstudio.com.
Step 1 − Once downloading is complete, run the installer. The following dialog will be displayed.
Step 2 − Click on the Install button and it will start the installation process.
Installation Process
Step 3 − Once the installation process is completed successfully, you will see the following
dialog. Close this dialog and restart your computer if required.
Setup Completed
Step 4 − Open Visual Studio from start Menu which will open the following dialog. It will be a
while for the first time for preparation.
Visual Studio
Step 5 − Once all is done you will see the main window of Visual studio.
Main Window
New Project
The new project window allows choosing an application template from the available templates.
Visual Studio IDE
When you start a new web site, ASP.NET provides the starting folders and files for the site,
including two files for the first web form of the site.
The file named Default.aspx contains the HTML and asp code that defines the form, and the file
named Default.aspx.cs (for C# coding) or the file named Default.aspx.vb (for VB coding)
contains the code in the language you have chosen and this code is responsible for the actions
performed on a form.
The primary window in the Visual Studio IDE is the Web Forms Designer window. Other
supporting windows are the Toolbox, the Solution Explorer, and the Properties window. You use
the designer to design a web form, to add code to the control on the form so that the form works
according to your need, you use the code editor.
To change the Web Forms Designer from one view to another, click on the Design or source
button.
To close a window, click on the close button on the upper right corner and to redisplay, select it
from the View menu.
To hide a window, click on its Auto Hide button. The window then changes into a tab. To display
again, click the Auto Hide button again.
When a new web form is created, Visual Studio automatically generates the starting HTML for
the form and displays it in Source view of the web forms designer. The Solution Explorer is used
to add any other files, folders or any existing item on the web site.
To add a standard folder, right-click on the project or folder under which you are going to add the
folder in the Solution Explorer and choose New Folder.
To add an ASP.NET folder, right-click on the project in the Solution Explorer and select the
folder from the list.
To add an existing item to the site, right-click on the project or folder under which you are going
to add the item in the Solution Explorer and select from the dialog box.
When a new website is created. VB2008 automatically creates the solution and displays it in the
solution explorer.
Solutions may contain one or more projects. A project contains content files, source files, and
other files like data sources and image files. Generally, the contents of a project are compiled
into an assembly as an executable file (.exe) or a dynamic link library (.dll) file.
Selecting Start
pressing F5
Ctrl-F5
The program is built meaning, the .exe or the .dll files are generated by selecting a command
from the Build menu.
ASP.NET - Life Cycle
User makes a request for accessing application resource, a page. Browser sends this request
to the web server.
A unified pipeline receives the first request and the following events take place:
o An object of the class ApplicationManager is created.
o An object of the class HostingEnvironment is created to provide information
regarding the resources.
o Top level items in the application are compiled.
Response objects are created. The application objects such as HttpContext, HttpRequest
and HttpResponse are created and initialized.
An instance of the HttpApplication object is created and assigned to the request.
The request is processed by the HttpApplication class. Different events are raised by this
class for processing the request.
When a page is requested, it is loaded into the server memory, processed, and sent to the
browser. Then it is unloaded from the memory. At each of these steps, methods and events are
available, which could be overridden according to the need of the application. In other words,
you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on
the page, except the directives, are part of this control tree. You can see the control tree by
adding trace= "true" to the page directive. We will cover page directives and tracing under
'directives' and 'event handling'.
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at
any stage of the page life cycle. It also helps in writing custom controls and initializing them at
right time, populate their properties with view-state data and run control behavior code.
Page request - When ASP.NET gets a page request, it decides whether to parse and
compile the page, or there would be a cached version of the page; accordingly the response
is sent.
Starting of page life cycle - At this stage, the Request and Response objects are set. If the
request is an old request or post back, the IsPostBack property of the page is set to true. The
UICulture property of the page is also set.
Page initialization - At this stage, the controls on the page are assigned unique ID by
setting the UniqueID property and the themes are applied. For a new request, postback data
is loaded and the control properties are restored to the view-state values.
Page load - At this stage, control properties are set using the view state and control state
values.
Validation - Validate method of the validation control is called and on its successful
execution, the IsValid property of the page is set to true.
Postback event handling - If the request is a postback (old request), the related event
handler is invoked.
Page rendering - At this stage, view state for the page and all controls are saved. The page
calls the Render method for each control and the output of rendering is written to the
OutputStream class of the Response property of page.
Unload - The rendered page is sent to the client and page properties, such as Response and
Request, are unloaded and all cleanup done.
At each stage of the page life cycle, the page raises some events, which could be coded. An event
handler is basically a function or subroutine, bound to the event, using declarative attributes such
as Onclick or handle.
PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and
determines whether the page is a postback. It sets the themes and master pages, creates
dynamic controls, and gets and sets profile property values. This event can be handled by
overloading the OnPreInit method or creating a Page_PreInit handler.
Init - Init event initializes the control property and the control tree is built. This event can
be handled by overloading the OnInit method or creating a Page_Init handler.
InitComplete - InitComplete event allows tracking of view state. All the controls turn on
view-state tracking.
LoadViewState - LoadViewState event allows loading view state information into the
controls.
LoadPostData - During this phase, the contents of all the input fields are defined with the
<form> tag are processed.
PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event
can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
Load - The Load event is raised for the page first and then recursively for all child controls.
The controls in the control tree are created. This event can be handled by overloading the
OnLoad method or creating a Page_Load handler.
LoadComplete - The loading process is completed, control event handlers are run, and
page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler
PreRender - The PreRender event occurs just before the output is rendered. By handling
this event, pages and controls can perform any updates before the output is rendered.
PreRenderComplete - As the PreRender event is recursively fired for all child controls,
this event ensures the completion of the pre-rendering phase.
SaveStateComplete - State of control on the page is saved. Personalization, control state
and view state information is saved. The HTML markup is generated. This stage can be
handled by overriding the Render method or creating a Page_Render handler.
UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad
event for all controls recursively and lastly for the page itself. Final cleanup is done and all
resources and references, such as database connections, are freed. This event can be
handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.
ASP.NET - 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">
<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:
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<br />
<br />
</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:
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);
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:
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:
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" %>
<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 />
</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 {
if (Page.IsPostBack) {
lblmessage.Text += "Page post back event handled.<br/>";
}
}
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
Method Description
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.
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
Method Description
Property Description
Method Description
AddHeader Adds an HTTP header to the output stream.
AddHeader is provided for compatibility with
earlier versions of ASP.
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" %>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
The code behind Button1_Click:
protected void Button1_Click(object sender, EventArgs e) {
if (!String.IsNullOrEmpty(TextBox1.Text)) {
Controls are small building blocks of the graphical user interface, which include text boxes,
buttons, check boxes, list boxes, labels, and numerous other tools. Using these tools, the users
can enter data, make selections and indicate their preferences.
Controls are also used for structural jobs, like validation, data access, security, creating master
pages, and data manipulation.
ASP.NET uses five types of web controls, which are:
HTML controls
HTML Server controls
ASP.NET Server controls
ASP.NET Ajax Server controls
User controls and custom controls
ASP.NET server controls are the primary controls used in ASP.NET. These controls can be
grouped into the following categories:
Validation controls - These are used to validate user input and they work by running
client-side script.
Data source controls - These controls provides data binding to different data sources.
Data view controls - These are various lists and tables, which can bind to data from data
sources for displaying.
Personalization controls - These are used for personalization of a page according to the
user preferences, based on user information.
Login and security controls - These controls provide user authentication.
Master pages - These controls provide consistent layout and interface throughout the
application.
Navigation controls - These controls help in navigation. For example, menus, tree view
etc.
Rich controls - These controls implement special features. For example, AdRotator,
FileUpload, and Calendar control.
The syntax for using server controls is:
<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] />
In addition, visual studio has the following features, to help produce in error-free coding:
AccessKey Pressing this key with the Alt key moves focus to the
control.
DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML
element when the control is disabled.
Font Font.
Site The container that hosts the current control when rendered
on a design surface.
TabIndex Gets or sets the tab index of the Web server control.
ToolTip Gets or sets the text displayed when the mouse pointer
hovers over the web server control.
Method Description
ApplyStyleSheetSkin Applies the style properties defined in the page style sheet
to the control.
CreateControlStyle Creates the style object that is used to implement all style
related properties.
DataBind Binds a data source to the server control and all its child
controls.
DataBind(Boolean) Binds a data source to the server control and all its child
controls with an option to raise the DataBinding event.
FindControl(String, Int32) Searches the current naming container for a server control
with the specified id and an integer.
RenderEndTag Renders the HTML closing tag of the control into the
specified writer.
SaveControlState Saves any server control state changes that have occurred
since the time the page was posted back to the server.
Example
Let us look at a particular server control - a tree view control. A Tree view control comes under
navigation controls. Other Navigation controls are: Menu control and SiteMapPath control.
Add a tree view control on the page. Select Edit Nodes... from the tasks. Edit each of the nodes
using the Tree view node editor as shown:
Once you have created the nodes, it looks like the following in design view:
The AutoFormat... task allows you to format the tree view as shown:
Add a label control and a text box control on the page and name them lblmessage and txtmessage
respectively.
Write a few lines of code to ensure that when a particular node is selected, the label control
displays the node text and the text box displays all child nodes under it, if any. The code behind
the file should look like this:
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 treeviewdemo : System.Web.UI.Page {
if(childnodes != null) {
txtmessage.Text = " ";
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" %>
<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.
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:
<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 />
</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">
<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.
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.
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.
Property Description
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.
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.
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
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 ("").
Property Description
Property Description
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.
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.
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.
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
AlternateTex 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.
ASP.NET – Validators
ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated,
or contradictory data don't get stored.
ASP.NET provides the following validation controls:
RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary
BaseValidator Class
The validation control classes are inherited from the BaseValidator class hence they inherit its
properties and methods. Therefore, it would help to take a look at the properties and the methods
of this base class, which are common for all the validation controls:
Members Description
ControlToValidate Indicates the input control to validate.
Display Indicates how the error message is shown.
EnableClientScrip Indicates whether client side validation will take.
Enabled Enables or disables the validator.
ErrorMessage Indicates error string.
Text Error text to be shown if validation fails.
IsValid Indicates whether the value of the control is valid.
SetFocusOnError It indicates whether in case of an invalid control, the focus should switch to
the related input control.
ValidationGroup The logical group of multiple validators, where this control belongs.
Validate() This method revalidates the control and updates the IsValid property.
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty. It is generally
tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined range.
It has three specific properties:
Properties Description
Type It defines the type of the data. The available values are: Currency, Date,
Double, Integer, and String.
</asp:RangeValidator>
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a value in
another control.
It has the following specific properties:
Properties Description
Type It specifies the data type.
ControlToCompare It specifies the value of the input control to compare with.
ValueToCompare It specifies the constant value to compare with.
Operator It specifies the comparison operator, the available values are:
Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan,
LessThanEqual, and DataTypeCheck.
</asp:CompareValidator>
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a pattern of
a regular expression. The regular expression is set in the ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular expressions:
Character Description
\b Matches a backspace.
\t Matches a tab.
\r Matches a carriage return.
\v Matches a vertical tab.
\f Matches a form feed.
\n Matches a new line.
\ Escape character.
Apart from single character match, a class of characters could be specified that can be matched,
called the metacharacters.
Metacharacter Description
. Matches any character except \n.
[abcd] Matches any character in the set.
[^abcd] Excludes any character in the set.
[2-7a-mA-M] Matches any character specified in the range.
\w Matches any alphanumeric character and underscore.
\W Matches any non-word character.
\s Matches whitespace characters like, space, tab, new line etc.
\S Matches any non-whitespace character.
\d Matches any decimal character.
\D Matches any non-decimal character.
Quantifiers could be added to specify number of times a character could appear.
Quantifier Description
* Zero or more matches.
+ One or more matches.
? Zero or one matches.
{N} N matches.
{N,} N or more matches.
{N,M} Between N and M matches.
The syntax of the control is as given:
<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">
</asp:RegularExpressionValidator>
CustomValidator
The CustomValidator control allows writing application specific custom validation routines for
both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction property. The
client side validation routine should be written in a scripting language, such as JavaScript or
VBScript, which the browser can understand.
The server side validation routine must be called from the control's ServerValidate event handler.
The server side validation routine should be written in any .Net language, like C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any validation but shows a summary of all
errors in the page. The summary displays the values of the ErrorMessage property of all
validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
ShowSummary : shows the error messages in specified format.
ShowMessageBox : shows the error messages in a separate window.
The syntax for the control is as given:
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />
Validation Groups
Complex pages have different groups of information provided in different panels. In such
situation, a need might arise for performing validation separately for separate group. This kind of
situation is handled using validation groups.
To create a validation group, you should put the input controls and the validation controls into
the same logical group by setting their ValidationGroup property.
Example
The following example describes a form to be filled up by all the students of a school, divided
into four houses, for electing the school president. Here, we use the validation controls to
validate the user input.
This is the form in design view:
<tr>
<td class="style1" colspan="3" align="center">
<asp:Label ID="lblmsg"
Text="President Election Form : Choose your president"
runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:DropDownList ID="ddlcandidate" runat="server" style="width:239px">
<asp:ListItem>Please Choose a Candidate</asp:ListItem>
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
House:
</td>
<td class="style2">
<asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvhouse" runat="server"
ControlToValidate="rblhouse" ErrorMessage="Enter your house name" >
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
<tr>
<td class="style3">
Class:
</td>
<td class="style2">
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
</td>
<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style3">
Email:
</td>
<td class="style2">
<asp:TextBox ID="txtemail" runat="server" style="width:250px">
</asp:TextBox>
</td>
<td>
<asp:RegularExpressionValidator ID="remail" runat="server"
ControlToValidate="txtemail" ErrorMessage="Enter your email"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td class="style3" align="center" colspan="3">
<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
style="text-align: center" Text="Submit" style="width:140px" />
</td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
</form>
The code behind the submit button:
protected void btnsubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblmsg.Text = "Thank You";
}
else
{
lblmsg.Text = "Fill up all the fields";
}
}
ASP.NET has two controls that allow users to upload files to the web server. Once the server
receives the posted file data, the application can save it, check it, or ignore it. The following
controls allow the file uploading:
HtmlInputFile - an HTML server control
FileUpload - and ASP.NET web control
Both controls allow file uploading, but the FileUpload control automatically sets the encoding of
the form, whereas the HtmlInputFile does not do so.
In this tutorial, we use the FileUpload control. The FileUpload control allows the user to browse
for and select the file to be uploaded, providing a browse button and a text box for entering the
filename.
Once, the user has entered the filename in the text box by typing the name or browsing, the
SaveAs method of the FileUpload control can be called to save the file to the disk.
The basic syntax of FileUpload is:
<asp:FileUpload ID= "Uploader" runat = "server" />
The FileUpload class is derived from the WebControl class, and inherits all its members. Apart
from those, the FileUpload class has the following read-only properties:
Properties Description
FileBytes Returns an array of the bytes in a file to be uploaded.
FileConten Returns the stream object pointing to the file to be uploaded.
FileName Returns the name of the file to be uploaded.
HasFile Specifies whether the control has a file to upload.
PostedFile Returns a reference to the uploaded file.
The posted file is encapsulated in an object of type HttpPostedFile, which could be accessed
through the PostedFile property of the FileUpload class.
The HttpPostedFile class has the following frequently used properties:
Properties Description
ContentLengt Returns the size of the uploaded file in bytes.
ContentType Returns the MIME type of the uploaded file.
FileName Returns the full filename.
InputStream Returns a stream object pointing to the uploaded file.
Example
The following example demonstrates the FileUpload control and its properties. The form has a
FileUpload control along with a save button and a label control for displaying the file name, file
type, and file length.
In the design view, the form looks as follows:
The content file code is as given:
<body>
<form id="form1" runat="server">
<div>
<h3> File Upload:</h3>
<br />
<asp:FileUpload ID="FileUpload1" runat="server" />
<br /><br />
<asp:Button ID="btnsave" runat="server" onclick="btnsave_Click" Text="Save"
style="width:85px" />
<br /><br />
<asp:Label ID="lblmessage" runat="server" />
</div>
</form>
</body>
The code behind the save button is as given:
protected void btnsave_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
if (FileUpload1.HasFile)
{
try
{
sb.AppendFormat(" Uploading file: {0}", FileUpload1.FileName);
ASP.NET - Ad Rotator
The AdRotator control randomly selects banner graphics from a list, which is specified in an
external XML schedule file. This external XML schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that
the link should follow in the AdvertisementFile and the Target property respectively.
The basic syntax of adding an AdRotator is as follows:
<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />
Before going into the details of the AdRotator control and its properties, let us look into the
construction of the advertisement file.
The Advertisement File
The advertisement file is an XML file, which contains the information about the advertisements
to be displayed.
Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-
based markup language that enables you to store data in a structured format by using meaningful
tags. The term 'extensible' implies that you can extend your ability to describe a document by
defining meaningful tags for the application.
XML is not a language in itself, like HTML, but a set of rules for creating new markup
languages. It is a meta-markup language. It allows developers to create custom tag sets for
special uses. It structures, stores, and transports the information.
Following is an example of XML file:
<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a structured text file with well-defined tags
delineating the data. There are the following standard XML elements that are commonly used in
the advertisement file:
Element Description
Advertisements Encloses the advertisement file.
Ad Delineates separate ad.
ImageUrl The path of image that will be displayed.
NavigateUrl The link that will be followed when the user clicks the ad.
AlternateText The text that will be displayed instead of the picture if it
cannot be displayed.
<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>
<Ad>
<ImageUrl>rose4.jpg</ImageUrl>
<NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>
Properties and Events of the AdRotator Class
The AdRotator class is derived from the WebControl class and inherits its properties. Apart from
those, the AdRotator class has the following properties:
Properties Description
AdvertisementFile The path to the advertisement file.
AlternateTextFeil The element name of the field where alternate text is provided. The default
d value is AlternateText.
DataMember The name of the specific list of data to be bound when advertisement file is
not used.
ImageUrlField The element name of the field where the URL for the image is provided.
The default value is ImageUrl.
Target The browser window or frame that displays the content of the page linked.
UniqueID Obtains the unique, hierarchically qualified identifier for the AdRotator
control.
Events Description
AdCreated It is raised once per round trip to the server after creation of
the control, but before the page is rendered
Load Occurs when the server control is loaded into the Page object.
PreRender Occurs after the Control object is loaded but prior to
rendering.
ASP.NET – Calendars
The calendar control is a functionally rich web control, which provides the following
capabilities:
Displaying one month at a time
Selecting a day, a week or a month
Selecting a range of days
Moving from month to month
Controlling the display of the days programmatically
The basic syntax of a calendar control is:
<asp:Calender ID = "Calendar1" runat = "server">
</asp:Calender>
Properties and Events of the Calendar Control
The calendar control has many properties and events, using which you can customize the actions
and display of the control. The following table provides some important properties of the
Calendar control:
Properties Description
Caption Gets or sets the caption for the calendar control.
CaptionAlign Gets or sets the alignment for the caption.
CellPadding Gets or sets the number of spaces between the data and the cell border.
CellSpacing Gets or sets the space between cells.
DayHeaderStyle Gets the style properties for the section that displays the day of the week.
DayNameFormat Gets or sets format of days of the week.
DayStyle Gets the style properties for the days in the displayed month.
FirstDayOfWeek Gets or sets the day of week to display in the first column.
NextMonthText Gets or sets the text for next month navigation control. The default value is >.
NextPrevFormat Gets or sets the format of the next and previous month navigation control.
OtherMonthDayStyle Gets the style properties for the days on the Calendar control that are not in
the displayed month.
PrevMonthText Gets or sets the text for previous month navigation control. The default value
is <.
SelectMonthText Gets or sets the text for the month selection element in the selector column.
SelectorStyle Gets the style properties for the week and month selector column.
SelectWeekText Gets or sets the text displayed for the week selection element in the selector
column.
ShowDayHeader Gets or sets the value indicating whether the heading for the days of the week
is displayed.
ShowGridLines Gets or sets the value indicating whether the gridlines would be shown.
ShowNextPrevMonth Gets or sets a value indicating whether next and previous month navigation
elements are shown in the title section.
ShowTitle Gets or sets a value indicating whether the title section is displayed.
TitleFormat Gets or sets the format for the title section.
Titlestyle Get the style properties of the title heading for the Calendar control.
TodayDayStyle Gets the style properties for today's date on the Calendar control.
TodaysDate Gets or sets the value for today's date.
UseAccessibleHeader Gets or sets a value that indicates whether to render the table header <th>
HTML element for the day headers instead of the table data <td> HTML
element.
VisibleDate Gets or sets the date that specifies the month to display.
WeekendDayStyle Gets the style properties for the weekend dates on the Calendar control.
The Calendar control has the following three most important events that allow the developers to
program the calendar control. They are:
Events Description
SelectionChanged It is raised when a day, a week or an entire month is selected.
DayRender It is raised when each data cell of the calendar control is rendered.
VisibleMonthChanged It is raised when user changes a month.
Properties Description
Day To select a single day.
DayWeek To select a single day or an entire week.
DayWeekMonth To select a single day, a week, or an entire month.
None Nothing can be selected.
The syntax for selecting days:
<asp:Calender ID = "Calendar1" runat = "server" SelectionMode="DayWeekMonth">
</asp:Calender>
When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol
appears for selecting the week, and a >> symbol appears to the left of the days name for selecting
the month.
Example
The following example demonstrates selecting a date and displays the date in a label:
The content file code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="calendardemo._Default" %>
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3> Your Birthday:</h3>
<asp:Calendar ID="Calendar1" runat="server SelectionMode="DayWeekMonth"
onselectionchanged="Calendar1_SelectionChanged">
</asp:Calendar>
</div>
</form>
</body>
</html>
The event handler for the event SelectionChanged:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
lblday.Text = Calendar1.TodaysDate.ToShortDateString();
lblbday.Text = Calendar1.SelectedDate.ToShortDateString();
}
When the file is run, it should produce the following output:
View State
Control State
Session State
Application State
View State
The view state is the state of the page and all its controls. It is automatically maintained across
posts by the ASP.NET framework.
When a page is sent back to the client, the changes in the properties of the page and its controls
are determined, and stored in the value of a hidden input field named _VIEWSTATE. When the
page is again posted back, the _VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
The entire application by setting the EnableViewState property in the <pages> section
of web.config file.
A page by setting the EnableViewState attribute of the Page directive, as <%@ Page
Language="C#" EnableViewState="false" %>
A control by setting the Control.EnableViewState property.
It is implemented using a view state object defined by the StateBag class which defines a
collection of view state items. The state bag is a data structure containing attribute value pairs,
stored as strings associated with objects.
The StateBag class has the following properties:
Properties Description
Item(name) The value of the view state item with the specified name.
This is the default property of the StateBag class.
Methods Description
Add(name, value) Adds an item to the view state collection and existing item
is updated.
SetDirty Sets the state of the StateBag object as well as the Dirty
property of each of the StateItem objects contained by it.
SetItemDirty Sets the Dirty property for the specified StateItem object in
the StateBag object.
Example
The following example demonstrates the concept of storing view state. Let us keep a counter,
which is incremented each time the page is posted back by clicking a button on the page. A label
control shows the value in the counter.
The markup file code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="statedemo._Default" %>
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>View State demo</h3>
Page Counter:
</form>
</body>
</html>
The code behind file for the example is shown here:
public partial class _Default : System.Web.UI.Page
{
public int counter
{
get
{
if (ViewState["pcounter"] != null)
{
return ((int)ViewState["pcounter"]);
}
else
{
return 0;
}
}
set
{
ViewState["pcounter"] = value;
}
}
Control State
Control state cannot be modified, accessed directly, or disabled.
Session State
When a user connects to an ASP.NET website, a new session object is created. When session
state is turned on, a new session state object is created for each new request. This session state
object becomes part of the context and it is available through the page.
Session state is generally used for storing application data such as inventory, supplier list,
customer record, or shopping cart. It can also keep information about the user and his
preferences, and keep the track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to
server and back as cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of
session state items.
The HttpSessionState class has the following properties:
Properties Description
Item(name) The value of the session state item with the specified name.
This is the default property of the HttpSessionState class.
Methods Description
Remove(name) Removes the specified item from the session state collection.
RemoveAll Removes all keys and values from the session-state collection.
The session state object is a name-value pair to store and retrieve some information from the
session state object. You could use the following code for the same:
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}
The above code stores only strings in the Session dictionary object, however, it can store all the
primitive data types and arrays composed of primitive data types, as well as the DataSet,
DataTable, HashTable, and Image objects, as well as any user-defined class that inherits from the
ISerializable object.
Example
The following example demonstrates the concept of storing session state. There are two buttons
on the page, a text box to enter string and a label to display the text stored from last session.
The mark up file code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<tr>
<td style="width: 209px">
<asp:Label ID="lblstr" runat="server" Text="Enter a String" style="width:94px">
</asp:Label>
</td>
<tr>
<td style="width: 209px"> </td>
<td style="width: 317px"> </td>
</tr>
<tr>
<td style="width: 209px">
<asp:Button ID="btnnrm" runat="server"
Text="No action button" style="width:128px" />
</td>
<tr>
<td style="width: 209px">
<asp:Label ID="lblsession" runat="server" style="width:231px" >
</asp:Label>
</td>
<tr>
<td style="width: 209px">
<asp:Label ID="lblshstr" runat="server">
</asp:Label>
</td>
</table>
</div>
</form>
</body>
</html>
It should look like the following in design view:
Application State
The ASP.NET application is the collection of all web pages, code and other files within a single
virtual directory on a web server. When information is stored in application state, it is available
to all the users.
To provide for the use of application state, ASP.NET creates an application state object for each
application from the HTTPApplicationState class and stores this object in server memory. This
object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global application
data like tax rate, discount rate etc. and to keep the track of users visiting the site.
The HttpApplicationState class has the following properties:
Properties Description
Item(name) The value of the application state item with the specified
name. This is the default property of the
HttpApplicationState class.
Count The number of items in the application state collection.
Methods Description
Clear Removes all the items from the application state collection.
Unlock() Unlocks the application state collection so all the users can
access it.
Application state data is generally maintained by writing handlers for the events:
Application_Start
Application_End
Application_Error
Session_Start
Session_End
The following code snippet shows the basic syntax for storing application state information:
Void Application_Start(object sender, EventArgs e)
{
Application["startMessage"] = "The application has started.";
}
Select Web User Control from the Add New Item dialog box and name it footer.ascx.
Initially, the footer.ascx contains only a Control directive.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="footer.ascx.cs"
Inherits="customcontroldemo.footer" %>
Add the following code to the file:
<table>
<tr>
<td align="center"> Copyright ©2010 TutorialPoints Ltd.</td>
</tr>
<tr>
<td align="center"> Location: Hyderabad, A.P </td>
</tr>
</table>
To add the user control to your web page, you must add the Register directive and an instance of
the user control to the page. The following code shows the content file:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="customcontroldemo._Default" %>
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
</div>
<Tfooter:footer ID="footer1" runat="server" />
</form>
</body>
</html>
When executed, the page shows the footer and this control could be used in all the pages of your
website.
Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into a Dynamic Link
Library (DLL) and used as any other ASP.NET server control. They could be created in either of
the following way:
By deriving a custom control from an existing control
By composing a new custom control combing two or more existing controls.
By deriving from the base control class.
To understand the concept, let us create a custom control, which will simply render a text
message on the browser. To create this control, take the following steps:
Create a new website. Right click the solution (not the project) at the top of the tree in the
Solution Explorer.
In the New Project dialog box, select ASP.NET Server Control from the project templates.
The above step adds a new project and creates a complete custom control to the solution, called
ServerControl1. In this example, let us name the project CustomControls. To use this control,
this must be added as a reference to the web site before registering it on a page. To add a
reference to the existing project, right click on the project (not the solution), and click Add
Reference.
Select the CustomControls project from the Projects tab of the Add Reference dialog box. The
Solution Explorer should show the reference.
To use the control on a page, add the Register directive just below the @Page directive:
<%@ Register Assembly="CustomControls" Namespace="CustomControls" TagPrefix="ccs"
%>
Further, you can use the control, similar to any other controls.
<form id="form1" runat="server">
<div>
<ccs:ServerControl1 runat="server" Text = "I am a Custom Server Control" />
</div>
</form>
When executed, the Text property of the control is rendered on the browser as shown:
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]
public class ServerControl1 : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
set
{
ViewState["Text"] = value;
}
}
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]
set
{
ViewState["Text"] = value;
}
}
if (strtoupper == strrev)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
}
When you change the code for the control, you must build the solution by clicking Build -->
Build Solution, so that the changes are reflected in your project. Add a text box and a button
control to the page, so that the user can provide a text, it is checked for palindrome, when the
button is clicked.
<form id="form1" runat="server">
<div>
Enter a word:
<br />
<asp:TextBox ID="TextBox1" runat="server" style="width:198px"> </asp:TextBox>
(2) The RenderContents method of the custom control class is overridden here, as you can add
your own methods and events.
(3) The RenderContents method takes a parameter of HtmlTextWriter type, which is responsible
for rendering on the browser.
ADO.NET
ADO.NET provides a bridge between the front end controls and the back end database. The
ADO.NET objects encapsulate all the data access operations and the controls interact with these
objects to display data, thus hiding the details of movement of data.
The following figure shows the ADO.NET objects at a glance:
Properties Description
CaseSensitive Indicates whether string comparisons within the data tables
are case-sensitive.
Events Gets the list of event handlers that are attached to this
component.
Methods Description
AcceptChanges Accepts all changes made since the DataSet was loaded or
this method was called.
GetChanges Returns a copy of the DataSet with all changes made since it
was loaded or the AcceptChanges method was called.
GetChanges(DataRowState) Gets a copy of DataSet with all changes made since it was
loaded or the AcceptChanges method was called, filtered by
DataRowState.
GetXMLSchema Returns the XSD schema for the XML representation of the
data.
Load(IDataReader, LoadOption, Fills a DataSet with values from a data source using the
DataTable[]) supplied IDataReader, using an array of DataTable instances
to supply the schema and namespace information.
Load(IDataReader, LoadOption, Fills a DataSet with values from a data source using the
String[]) supplied IDataReader, using an array of strings to supply the
names for the tables within the DataSet.
Merge() Merges the data with data from another DataSet. This method
has different overloaded forms.
ReadXML() Reads an XML schema and data into the DataSet. This
method has different overloaded forms.
ReadXMLSchema(0) Reads an XML schema into the DataSet. This method has
different overloaded forms.
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
WriteXML() Writes an XML schema and data from the DataSet. This
method has different overloaded forms.
WriteXMLSchema() Writes the structure of the DataSet as an XML schema. This
method has different overloaded forms.
Properties Description
PrimaryKey Gets or sets an array of columns as the primary key for the
table.
The following table shows some important methods of the DataTable class:
Methods Description
LoadDataRow Finds and updates a specific row, or creates a new one, if not
found any.
RejectChanges Rolls back all changes made since the last call to
AcceptChanges.
Properties Description
HasErrors Indicates if there are any errors.
Items Gets or sets the data stored in a specific column.
ItemArrays Gets or sets all the values for the row.
Table Returns the parent table.
The following table shows some important methods of the DataRow class:
Methods Description
AcceptChanges Accepts all changes made since this method was called.
BeginEdit Begins edit operation.
CancelEdit Cancels edit operation.
Delete Deletes the DataRow.
EndEdit Ends the edit operation.
GetChildRows Gets the child rows of this row.
GetParentRow Gets the parent row.
GetParentRows Gets parent rows of DataRow object.
RejectChanges Rolls back all changes made since the last call to
The DataAdapter Object
The DataAdapter object acts as a mediator between the DataSet object and the database. This
helps the Dataset to contain data from multiple databases or other data source.
The DataReader Object
The DataReader object is an alternative to the DataSet and DataAdapter combination. This object
provides a connection oriented access to the data records in the database. These objects are
suitable for read-only access, such as populating a list and then breaking the connection.
DbCommand and DbConnection Objects
The DbConnection object represents a connection to the data source. The connection could be
shared among different command objects.
The DbCommand object represents the command or a stored procedure sent to the database from
retrieving or manipulating data.
Example
So far, we have used tables and databases already existing in our computer. In this example, we
will create a table, add column, rows and data into it and display the table using a GridView
object.
The source file code is as given:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="createdatabase._Default" %>
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
The code behind file is as given:
namespace createdatabase
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
GridView1.DataSource = ds.Tables["Student"];
GridView1.DataBind();
}
}
// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "System.String", "StudentName");
AddNewColumn(Students, "System.String", "StudentCity");
// adding rows
AddNewRow(Students, 1, "M H Kabir", "Kolkata");
AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad");
AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");
AddNewRow(Students, 1, "Rajat Mishra", "Patna");
return Students;
}
<head runat="server">
<title>
Tracing, debugging and error handling
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblheading" runat="server" Text="Tracing, Debuggin and Error
Handling">
</asp:Label>
</form>
</body>
</html>
The code behind file:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string[,] quotes =
{
{"Imagination is more important than Knowledge.", "Albert Einsten"},
{"Assume a virtue, if you have it not" "Shakespeare"},
{"A man cannot be comfortable without his own approval", "Mark Twain"},
{"Beware the young doctor and the old barber", "Benjamin Franklin"},
{"Whatever begun in anger ends in shame", "Benjamin Franklin"}
};
Tracing
To enable page level tracing, you need to modify the Page directive and add a Trace attribute as
shown:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="errorhandling._Default" Trace ="true" %>
Now when you execute the file, you get the tracing information:
It provides the following information at the top:
Session ID
Status Code
Time of Request
Type of Request
Request and Response Encoding
The status code sent from the server, each time the page is requested shows the name and time of
error if any. The following table shows the common HTTP status codes:
Number Description
Informational (100 - 199)
100 Continue
101 Switching protocols
Successful (200 - 299)
200 OK
204 No content
Redirection (300 - 399)
301 Moved permanently
305 Use proxy
307 Temporary redirect
Client Errors (400 - 499)
400 Bad request
402 Payment required
404 Not found
408 Request timeout
417 Expectation failed
Server Errors (500 - 599)
500 Internal server error
503 Service unavailable
505 HTTP version not supported
Under the top level information, there is Trace log, which provides details of page life cycle. It
provides elapsed time in seconds since the page was initialized.
The next section is control tree, which lists all controls on the page in a hierarchical manner:
Last in the Session and Application state summaries, cookies, and headers collections followed
by list of all server variables.
The Trace object allows you to add custom information to the trace output. It has two methods to
accomplish this: the Write method and the Warn method.
Change the Page_Load event handler to check the Write method:
protected void Page_Load(object sender, EventArgs e)
{
Trace.Write("Page Load");
if (!IsPostBack)
{
Trace.Write("Not Post Back, Page Load");
string[,] quotes =
.......................
}
}
Run to observe the effects:
To check the Warn method, let us forcibly enter some erroneous code in the selected index
changed event handler:
try
{
int a = 0;
int b = 9 / a;
}catch (Exception e)
{
Trace.Warn("UserAction", "processing 9/a", e);
}
Try-Catch is a C# programming construct. The try block holds any code that may or may not
produce error and the catch block catches the error. When the program is run, it sends the
warning in the trace log.
Application level tracing applies to all the pages in the web site. It is implemented by putting the
following code lines in the web.config file:
<system.web>
<trace enabled="true" />
</system.web>
Error Handling
Although ASP.NET can detect all runtime errors, still some subtle errors may still be there.
Observing the errors by tracing is meant for the developers, not for the users.
Hence, to intercept such occurrence, you can add error handing settings in the web.config file of
the application. It is application-wide error handling. For example, you can add the following
lines in the web.config file:
<configuration>
<system.web>
</system.web>
<configuration>
The <customErrors> section has the possible attributes:
Mode : It enables or disables custom error pages. It has the three possible values:
o On : displays the custom pages.
o Off : displays ASP.NET error pages (yellow pages)
o remoteOnly : It displays custom errors to client, display ASP.NET errors locally.
defaultRedirect : It contains the URL of the page to be displayed in case of unhandled
errors.
To put different custom error pages for different type of errors, the <error> sub tags are used,
where different error pages are specified, based on the status code of the errors.
To implement page level error handling, the Page directive could be modified:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="errorhandling._Default" Trace ="true" ErrorPage="PageError.htm" %>
ASP.NET – Security
Implementing security in a site has the following aspects:
Authentication : It is the process of ensuring the user's identity and authenticity.
ASP.NET allows four types of authentications:
o Windows Authentication
o Forms Authentication
o Passport Authentication
o Custom Authentication
Authorization : It is the process of defining and allotting specific roles to specific users.
Confidentiality : It involves encrypting the channel between the client browser and the
web server.
Integrity : It involves maintaining the integrity of data. For example, implementing
digital signature.
Forms-Based Authentication
Traditionally, forms-based authentication involves editing the web.config file and adding a login
page with appropriate authentication code.
The web.config file could be edited and the following codes written on it:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl ="login.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
...
...
</configuration>
The login.aspx page mentioned in the above code snippet could have the following code behind
file with the usernames and passwords for authentication hard coded into it.
protected bool authenticate(String uname, String pass)
{
if(uname == "Tom")
{
if(pass == "tom123")
return true;
}
if(uname == "Dick")
{
if(pass == "dick123")
return true;
}
if(uname == "Harry")
{
if(pass == "har123")
return true;
}
return false;
}
Step (4) : Click on 'Create Users' link to create some users. If you already had created roles, you
could assign roles to the user, right at this stage.
Step (5) : Create a web site and add the following pages:
Welcome.aspx
Login.aspx
CreateAccount.aspx
PasswordRecovery.aspx
ChangePassword.aspx
Step (6) : Place a LoginStatus control on the Welcome.aspx from the login section of the
toolbox. It has two templates: LoggedIn and LoggedOut.
In LoggedOut template, there is a login link and in the LoggedIn template, there is a logout link
on the control. You can change the login and logout text properties of the control from the
Properties window.
Step (7) : Place a LoginView control from the toolbox below the LoginStatus control. Here, you
can put texts and other controls (hyperlinks, buttons etc.), which are displayed based on whether
the user is logged in or not.
This control has two view templates: Anonymous template and LoggedIn template. Select each
view and write some text for the users to be displayed for each template. The text should be
placed on the area marked red.
Step (8) : The users for the application are created by the developer. You might want to allow a
visitor to create a user account. For this, add a link beneath the LoginView control, which should
link to the CreateAccount.aspx page.
Step (9) : Place a CreateUserWizard control on the create account page. Set the
ContinueDestinationPageUrl property of this control to Welcome.aspx.
Step (10) : Create the Login page. Place a Login control on the page. The LoginStatus control
automatically links to the Login.aspx. To change this default, make the following changes in the
web.config file.
For example, if you want to name your log in page as signup.aspx, add the following lines to the
<authentication> section of the web.config:
<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl ="signup.aspx" defaultUrl = “Welcome.aspx†/>
</authentication>
</system.web>
</configuration>
Step (11) : Users often forget passwords. The PasswordRecovery control helps the user gain
access to the account. Select the Login control. Open its smart tag and click 'Convert to
Template'.
Customize the UI of the control to place a hyperlink control under the login button, which should
link to the PassWordRecovery.aspx.
Step (12) : Place a PasswordRecovery control on the password recovery page. This control needs
an email server to send the passwords to the users.
Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the
LoginView control in Welcome.aspx.
Step (14) : Place a ChangePassword control on the change password page. This control also has
two views.
Now run the application and observe different security operations.
To create roles, go back to the Web Application Administration Tools and click on the Security
tab. Click on 'Create Roles' and create some roles for the application.
Click on the 'Manage Users' link and assign roles to the users.
www.verisign.com
www.geotrust.com
www.thawte.com
SSL is built into all major browsers and servers. To enable SSL, you need to install the digital
certificate. The strength of various digital certificates varies depending upon the length of the
key generated during encryption. More the length, more secure is the certificate, hence the
connection.
Strength Description
40 bit Supported by most browsers but easy to break.
56 bit Stronger than 40-bit.
128 bit Extremely difficult to break but all the browsers do not
support it.
DiskCacheable true/false Specifies that output could be written to a disk based cache.
NoStore true/false Specifies that the "no store" cache control header is sent or not.
VaryByCustom Tells ASP.NET to vary the output cache by browser name and
Browser
version or by a custom string.
Custom
string
Let us add a text box and a button to the previous example and add this event handler for the
button.
protected void btnmagic_Click(object sender, EventArgs e)
{
Response.Write("<br><br>");
Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>");
}
Change the OutputCache directive:
<%@ OutputCache Duration="60" VaryByParam="txtname" %>
When the program is executed, ASP.NET caches the page on the basis of the name in the text
box.
Data Caching
The main aspect of data caching is caching the data source controls. We have already discussed
that the data source controls represent data in a data source, like a database or an XML file.
These controls derive from the abstract class DataSourceControl and have the following
inherited properties for implementing caching:
CacheDuration - It sets the number of seconds for which the data source will cache data.
CacheExpirationPolicy - It defines the cache behavior when the data in cache has
expired.
CacheKeyDependency - It identifies a key for the controls that auto-expires the content
of its cache when removed.
EnableCaching - It specifies whether or not to cache the data.
Example
To demonstrate data caching, create a new website and add a new web form on it. Add a
SqlDataSource control with the database connection already used in the data access tutorials.
For this example, add a label to the page, which would show the response time for the page.
<asp:Label ID="lbltime" runat="server"></asp:Label>
Apart from the label, the content page is same as in the data access tutorial. Add an event handler
for the page load event:
protected void Page_Load(object sender, EventArgs e)
{
lbltime.Text = String.Format("Page posted at: {0}", DateTime.Now.ToLongTimeString());
}
The designed page should look as shown:
When you execute the page for the first time, nothing different happens, the label shows that,
each time you refresh the page, the page is reloaded and the time shown on the label changes.
Next, set the EnableCaching attribute of the data source control to be 'true' and set the
Cacheduration attribute to '60'. It will implement caching and the cache will expire every 60
seconds.
The timestamp changes with every refresh, but if you change the data in the table within these 60
seconds, it is not shown before the cache expires.
<asp:SqlDataSource ID = "SqlDataSource1" runat = "server"
ConnectionString = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString %>"
ProviderName = "<%$ ConnectionStrings:
ASPDotNetStepByStepConnectionString.ProviderName %>"
SelectCommand = "SELECT * FROM [DotNetReferences]"
EnableCaching = "true" CacheDuration = "60">
</asp:SqlDataSource>
Object Caching
Object caching provides more flexibility than other cache techniques. You can use object
caching to place any object in the cache. The object can be of any type - a data type, a web
control, a class, a dataset object, etc. The item is added to the cache simply by assigning a new
key name, shown as follows Like:
Cache["key"] = item;
ASP.NET also provides the Insert() method for inserting an object to the cache. This method has
four overloaded versions. Let us see them:
Overload Description
Cache.Insert((key, value); Inserts an item into the cache with the key name and
value with default priority and expiration.
Cache.Insert(key, value, dependencies); Inserts an item into the cache with key, value, default
priority, expiration and a CacheDependency name that
links to other files or items so that when these change
the cache item remains no longer valid.
Cache.Insert(key, value, dependencies, This indicates an expiration policy along with the
absoluteExpiration, slidingExpiration); above issues.
Cache.Insert(key, value, dependencies, This along with the parameters also allows you to set a
absoluteExpiration, slidingExpiration, priority for the cache item and a delegate that, points
priority, onRemoveCallback); to a method to be invoked when the item is removed.
Sliding expiration is used to remove an item from the cache when it is not used for the specified
time span. The following code snippet stores an item with a sliding expiration of 10 minutes with
no dependencies.
Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));
Example
Create a page with just a button and a label. Write the following code in the page load event:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
lblinfo.Text += "Page Posted Back.<br/>";
}
else
{
lblinfo.Text += "page Created.<br/>";
}
if (Cache["testitem"] == null)
{
lblinfo.Text += "Creating test item.<br/>";
DateTime testItem = DateTime.Now;
lblinfo.Text += "Storing test item in cache ";
lblinfo.Text += "for 30 seconds.<br/>";
Cache.Insert("testitem", testItem, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
}
else
{
lblinfo.Text += "Retrieving test item.<br/>";
DateTime testItem = (DateTime)Cache["testitem"];
lblinfo.Text += "Test item is: " + testItem.ToString();
lblinfo.Text += "<br/>";
}
lblinfo.Text += "<br/>";
}
When the page is loaded for the first time, it says:
Page Created.
Creating test item.
Storing test item in cache for 30 seconds.
If you click on the button again within 30 seconds, the page is posted back but the label control
gets its information from the cache as shown:
Page Posted Back.
Retrieving test item.
Test item is: 14-07-2010 01:25:04