0% found this document useful (0 votes)
8 views38 pages

ASP Unit - 4

ASP.NET is a web development platform by Microsoft used for creating web applications, first released in 2002. It supports multiple .NET languages and includes features like state management, caching, and a structured page lifecycle. The document also provides an example of creating a simple 'Hello World' application and describes various server controls available in ASP.NET web forms.

Uploaded by

sumaiya10601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views38 pages

ASP Unit - 4

ASP.NET is a web development platform by Microsoft used for creating web applications, first released in 2002. It supports multiple .NET languages and includes features like state management, caching, and a structured page lifecycle. The document also provides an example of creating a simple 'Hello World' application and describes various server controls available in ASP.NET web forms.

Uploaded by

sumaiya10601
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Unit - 4

ASP.NET - Introduction

ASP.Net is a web development platform provided by Microsoft. It is used for creating web-based applications.
ASP.Net was first released in the year 2002.

The first version of ASP.Net deployed was 1.0. The most recent version of ASP.Net is version 4.6. ASP.Net is
designed to work with the HTTP protocol. This is the standard protocol used across all web applications.

ASP.Net applications can also be written in a variety of .Net languages. These include C#, VB.Net, and J#. In this
chapter, you will see some basic fundamental of the .Net framework.

The full form of ASP is Active Server Pages, and .NET is Network Enabled Technologies.

ASP.NET Architecture and its Components

ASP.Net is a framework which is used to develop a Web-based application. The basic architecture of the ASP.Net
framework is as shown below.

ASP.NET Architecture Diagram

The architecture of the.Net framework is based on the following key components

1. Language – A variety of languages exists for .net framework. They are VB.net and C#. These can be used to
develop web applications.
2. Library - The .NET Framework includes a set of standard class libraries. The most common library used for
web applications in .net is the Web library. The web library has all the necessary components used to
develop.Net web-based applications.
3. Common Language Runtime - The Common Language Infrastructure or CLI is a platform. .Net programs
are executed on this platform. The CLR is used for performing key activities. Activities include Exception
handling and Garbage collection.

Below are some of the key characteristics of the ASP.Net framework

1. Code Behind Mode – This is the concept of separation of design and code. By making this separation, it
becomes easier to maintain the ASP.Net application. The general file type of an ASP.Net file is aspx.
Assume we have a web page called MyPage.aspx. There will be another file called MyPage.aspx.cs which
would denote the code part of the page. So Visual Studio creates separate files for each web page, one for the
design part and the other for the code.
2. State Management – ASP.Net has the facility to control state management. HTTP is known as a stateless
protocol. Let's take an example of a shopping cart application. Now, when a user decides what he wants to
buy from the site, he will press the submit button.

The application needs to remember the items the user choose for the purchase. This is known as
remembering the state of an application at a current point in time. HTTP is a stateless protocol. When the
user goes to the purchase page, HTTP will not store the information on the cart items. Additional coding
needs to be done to ensure that the cart items can be carried forward to the purchase page. Such an
implementation can become complex at times. But ASP.Net can do state management on your behalf. So
ASP.Net can remember the cart items and pass it over to the purchase page.

3. Caching – ASP.Net can implement the concept of Caching. This improve's the performance of the
application. By caching those pages which are often requested by the user can be stored in a temporary
location. These pages can be retrieved faster and better responses can be sent to the user. So caching can
significantly improve the performance of an application.

ASP.Net is a development language used for constructing web-based applications. ASP.Net is designed to work with
the standard HTTP protocol.

ASP.Net Lifecycle
When an ASP.Net application is launched, there are series of steps which are carried out. These series of steps make
up the lifecycle of the application.

Let's look at the various stages of a typical page lifecycle of an ASP.Net Web Application.

ASP.Net Lifecycle

1) Application Start - The life cycle of an ASP.NET application starts when a request is made by a user. This
request is to the Web server for the ASP.Net Application. This happens when the first user normally goes to the
home page for the application for the first time. During this time, there is a method called Application_start which is
executed by the web server. Usually, in this method, all global variables are set to their default values.

2) Object creation - The next stage is the creation of the HttpContext, HttpRequest & HttpResponse by the web
server. The HttpContext is just the container for the HttpRequest and HttpResponse objects. The HttpRequest object
contains information about the current request, including cookies and browser information. The HttpResponse object
contains the response that is sent to the client.

3) HttpApplication creation - This object is created by the web server. It is this object that is used to process each
subsequent request sent to the application. For example, let's assume we have 2 web applications. One is a shopping
cart application, and the other is a news website. For each application, we would have 2 HttpApplication objects
created. Any further requests to each website would be processed by each HttpApplication respectively.
4) Dispose - This event is called before the application instance is destroyed. During this time, one can use this
method to manually release any unmanaged resources.

5) Application End - This is the final part of the application. In this part, the application is finally unloaded from
memory.

ASP.Net Page Lifecycle


When an ASP.Net page is called, it goes through a particular lifecycle. This is done before the response is sent to the
user. There are series of steps which are followed for the processing of an ASP.Net page.

Let's look at the various stages of the lifecycle of an ASP.Net web page.

ASP.Net Page Lifecycle

1. Page Request- This is when the page is first requested from the server. When the page is requested, the
server checks if it is requested for the first time. If so, then it needs to compile the page, parse the response
and send it across to the user. If it is not the first time the page is requested, the cache is checked to see if the
page output exists. If so, that response is sent to the user.
2. Page Start – During this time, 2 objects, known as the Request and Response object are created. The
Request object is used to hold all the information which was sent when the page was requested. The
Response object is used to hold the information which is sent back to the user.
3. Page Initialization – During this time, all the controls on a web page is initialized. So if you have any label,
textbox or any other controls on the web form, they are all initialized.
4. Page Load – This is when the page is actually loaded with all the default values. So if a textbox is supposed
to have a default value, that value is loaded during the page load time.
5. Validation – Sometimes there can be some validation set on the form. For example, there can be a validation
which says that a list box should have a certain set of values. If the condition is false, then there should be an
error in loading the page.
6. Postback event handling – This event is triggered if the same page is being loaded again. This happens in
response to an earlier event. Sometimes there can be a situation that a user clicks on a submit button on the
page. In this case, the same page is displayed again. In such a case, the Postback event handler is called.
7. Page Rendering – This happens just before all the response information is sent to the user. All the
information on the form is saved, and the result is sent to the user as a complete web page.
8. Unload – Once the page output is sent to the user, there is no need to keep the ASP.net web form objects in
memory. So the unloading process involves removing all unwanted objects from memory.
ASP.NET First Program Example: Hello World
Let's look at an example of how we can implement a simple "hello world" application. For this, we would need to
implement the below-mentioned steps.

Step 1) The first step involves the creation of a new project in Visual Studio. After launching Visual Studio, you
need to choose the menu option New->Project.

Step 2) The next step is to choose the project type as an ASP.Net Web application. Here we also need to mention the
name and location of our project.

1. In the project dialog box, you can see various options for creating different types of projects. Click the Web
option on the left-hand side.
2. When we click the Web option in the previous step, we will be able to see an option for ASP.Net Web
Application. Click this option.
3. We then give a name for the application, which in our case is DemoApplication. We also need to provide a
location to store our application.
4. Finally, we click the 'OK' button to let Visual Studio to create our project.
Step 3) In the next screen, you have to choose the type of ASP.net web application that needs to be created. In our
case, we are going to create a simple Web Form application.

1. First, choose the project type as 'Empty'. This will ensure that we start with a basic application which is
simple to understand.
2. We choose the option "web Forms". This adds the basic folders. These are required for a basic Web Forms
Application.
3. Finally, we click the 'OK' button to allow Visual Studio to create our application.

If the above steps are followed, you will get the below output in Visual Studio.
Output:-

In the Solution Explorer, you will be able to see the DemoApplication Solution. This solution will contain 2 project
files as shown above. At the moment, one of the key files in the project is the 'Global.asax.cs'. This file contains
application specific information. In this file, you would initialize all application specific variables to their default
values.

Step 4) Now, it's time to add a Web Form file to the project. This is the file which will contain all the web-specific
code for our project.

 Right-click on the DemoApplication project and


 Choose Add->Web Form from the context menu.

Step 5) In the next screen we are going to be prompted to provide a name for the web form.

1. Give a name for the Web Form. In our case, we are giving it a name of Demo.
2. Click the Ok button.
Automatically Visual Studio will create the Demo Web Form and will open it in Visual Studio.

Step 6) The next step is to add the code, which will do the work of displaying "Hello World." This can be done by
just adding one line of code to the Demo.aspx file.

<html xmlns="www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<%Response. Write( "HeIIo World"); %>

</div>
</form>
</body>
</html>

Code Explanation:-

 The Response object in ASP.Net is used to send information back to


the user. So in our case, we are using the method "Write" of the
Response object to write the text "Hello World." The <% and %>
markers are used to add ASP.net specific code.

If you follow all of the above steps and run your program in Visual
Studio, you will get the following output.

Output:-

From the output, you can clearly see that 'Hello World' was displayed in the browser.

ASP.NET Web Forms Server Controls


ASP.NET provides web forms controls that are used to create HTML components. These controls are categories as
server and client based. The following table contains the server controls for the web forms.

Control Name Applicable Events Description

Label None It is used to display text on the HTML page.

TextBox TextChanged It is used to create a text input in the form.

Button Click, Command It is used to create a button.

LinkButton Click, Command It is used to create a button that looks similar to the
hyperlink.

ImageButton Click It is used to create an imagesButton. Here, an image


works as a Button.

Hyperlink None It is used to create a hyperlink control that responds to


a click event.

DropDownList SelectedIndexChanged It is used to create a dropdown list control.

ListBox SelectedIndexCnhaged It is used to create a ListBox control like the HTML


control.

DataGrid CancelCommand, It used to create a frid that is used to show data. We


EditCommand, can also perform paging, sorting, and formatting very
DeleteCommand, easily with this control.
ItemCommand,
SelectedIndexChanged,
PageIndexChanged,
SortCommand,
UpdateCommand,
ItemCreated, ItemDataBound

DataList CancelCommand, It is used to create datalist that is non-tabular and used


EditCommand, to show data.
DeleteCommand,
ItemCommand,
SelectedIndexChanged,
UpdateCommand,
ItemCreated, ItemDataBound

CheckBox CheckChanged It is used to create checkbox.

CheckBoxList SelectedIndexChanged It is used to create a group of check boxes that all work
together.

RadioButton CheckChanged It is used to create radio button.

RadioButtonList SelectedIndexChanged It is used to create a group of radio button controls that


all work together.

Image None It is used to show image within the page.

Panel None It is used to create a panel that works as a container.

PlaceHolder None It is used to set placeholder for the control.

Calendar SelectionChanged, It is used to create a calendar. We can set the default


VisibleMonthChanged, date, move forward and backward etc.
DayRender

Table None It is used to create table.

XML None It is used to display XML documents within the


HTML.

ASP.NET Web Forms Label

This control is used to display textual information on the web forms. It is mainly used to create caption for the other
controls like: textbox.

To create label either we can write code or use the drag and drop facility of visual studio 2017.

This is server side control, asp provides own tag to create label. The example is given below.
1. < asp:LabelID="Label1" runat="server" Text="Label" ></asp:Label>

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the label.

TabIndex The tab order of the control.

BackColor It is used to set background color of the label.

BorderColor It is used to set border color of the label.

BorderWidth It is used to set width of border of the label.

Font It is used to set font for the label text.

ForeColor It is used to set color of the label text.

Text It is used to set text to be shown for the label.

ToolTip It displays the text when mouse is over the label.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

Example

// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
margin-left: 0px;
}
.auto-style3 {
width: 121px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<h4>Provide the Following Details:</h4>
<table class="auto-style1">
<tr>
<td class="auto-style3">
<asp:Label ID="Label1" runat="server" Text="User Name"></asp:Label></td>
<td>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style2"></asp:TextBox></td>
</tr>
<tr>
<td class="auto-style3">
<asp:Label ID="Label2" runat="server" Text="Upload a File"></asp:Label></td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>

This is a property window of label control.

Output:

Here, we have used label control with two different controls. It produces the
following output.
ASP.NET Web Forms TextBox
This is an input control which is used to take user input. To create TextBox either we can write code or use the drag
and drop facility of visual studio IDE.

This is server side control, asp provides own tag to create it. The example is given below.

1. < asp:TextBoxID="TextBox1" runat="server" ></asp:TextBox>

Server renders it as the HTML control and produces the following code to the browser.

1. <input name="TextBox1" id="TextBox1" type="text">

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

MaxLength It is used to set maximum number of characters that can be entered.

Readonly It is used to make control readonly.

Example

// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="labelId" runat="server">User Name</asp:Label>
<asp:TextBox ID="UserName" runat="server" ToolTip="Enter User Name"></asp:TextBox>
</div>
<p>
<asp:Button ID="SubmitButton" runat="server" Text="Submit" OnClick="SubmitButton_Click" />
</p>
<br />
</form>
<asp:Label ID="userInput" runat="server"></asp:Label>
</body>
</html>

Code Behind

// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void SubmitButton_Click(object sender, EventArgs e)
{
userInput.Text = UserName.Text;
}
}
}

This is a property window of the TextBox control.

Output:
It produces the following output.

It displays user input, when user submits the input to the server. The following screen shot taking and showing user
input.

ASP.NET Web Forms Button

This control is used to perform events. It is also used to submit client request to the server. To create Button either
we can write code or use the drag and drop facility of visual studio IDE.

This is a server side control and asp provides own tag to create it. The example is given below.

1. < asp:ButtonID="Button1" runat="server" Text="Submit" BorderStyle="Solid" ToolTip="Submit"/>

Server renders it as the HTML control and produces the following code to the browser.

1. <input name="Button1" value="Submit" id="Button1" title="Submit" style="border-style:Solid;" type="submit">

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.


ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

Example

// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Click here" OnClick="Button1_Click" />
</div>
</form>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</body>
</html>

Code Behind

// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "You Clicked the Button.";
}
}
}

Output:

It produces the following output.

This button displays a message when clicked, as


shown below.

ASP.NET Web Forms RadioButton

It is an input control which is used to takes input from the user. It allows user to select a choice from the group of
choices.

To create RadioButton we can drag it from the toolbox of visual studio.

This is a server side control and ASP.NET provides own tag to create it. The example is given below.

1. < asp:RadioButtonID="RadioButton1" runat="server" Text="Male" GroupName="gender"/>

Server renders it as the HTML control and produces the following code to the browser.

1. <input id="RadioButton1" type="radio" name="gender" value="RadioButton1" /><labelforlabelfor="RadioButton


1">Male</label>

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.


ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

GroupName It is used to set name of the radio button group.

Example

In this example, we are creating two radio buttons and putting in a group named gender.

// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" Text="Male" GroupName="gender" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="Female" GroupName="gender" />
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" style="width: 61px" /
>
</p>
</form>
<asp:Label runat="server" id="genderId"></asp:Label>
</body>
</html>

Code Behind

// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
genderId.Text = "";
if (RadioButton1.Checked)
{
genderId.Text = "Your gender is "+RadioButton1.Text;
}
else genderId.Text = "Your gender is "+RadioButton2.Text;

}
}
}

For this control we have set some properties like this:

Output:

It produces the following output to the browser.

It responses back to the client when user select the gender.

ASP.NET Web Forms CheckBox

It is used to get multiple inputs from the user. It allows user to select choices from the set of choices.

It takes user input in yes or no format. It is useful when we want multiple choices from the user.

To create CheckBox we can drag it from the toolbox in visual studio.

This is a server side control and ASP.NET provides own tag to create it. The example is given below.
1. < asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE"/>

Server renders it as the HTML control and produces the following code to the browser.

1. < input id="CheckBox2" type="checkbox" name="CheckBox2" /><label for="CheckBox2">J2EE</label>

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.

BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

Checked It is used to set check state of the control either true or false.

Example

// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Select Courses</h2>
<asp:CheckBox ID="CheckBox1" runat="server" Text="J2SE" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="J2EE" />
<asp:CheckBox ID="CheckBox3" runat="server" Text="Spring" />
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</p>
</form>
<p>
Courses Selected: <asp:Label runat="server" ID="ShowCourses"></asp:Label>
</p>
</body>
</html>

Code Behind

// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShowCourses.Text = "None";
}
protected void Button1_Click(object sender, EventArgs e)
{
var message = "" ;
if (CheckBox1.Checked)
{
message = CheckBox1.Text+" ";
}
if (CheckBox2.Checked)
{
message += CheckBox2.Text + " ";
}
if (CheckBox3.Checked)
{
message += CheckBox3.Text;
}
ShowCourses.Text = message;
}
}
}

Initially, there is no course selected then it shows none. It displays user selection as shown in the following
screenshot.

ASP.NET Web Forms Calendar

It is used to display selectable date in a calendar. It also shows data associated with specific date. This control
displays a calendar through which users can move to any day in any year.

We can also set Selected Date property that shows specified date in the calendar.

To create Calendar we can drag it from the toolbox of visual studio.

This is a server side control and ASP.NET provides own tag to create it. The example is given below.

1. < asp:CalendarID="Calendar1" runat="server" SelectedDate="2017-06-15" ></asp:Calendar>

Server renders it as the HTML control and produces the following code to the browser.

1. <table id="Calendar1" cellspacing="0" cellpadding="2" title="Calendar"


2. style="border-width:1px;border-style:solid;border-collapse:collapse;">
3. <tr><td colspan="7" style="background-color:Silver;">
4. <table cellspacing="0" style="width:100%;border-collapse:collapse;">
5. <tr><td style="width:15%;">
6. <a href="javascript:__doPostBack('Calendar1','V6330')"
7. style="color:Black" title="Go to the previous month"></a> ...

This control has its own properties that are tabled below.

Property Description

AccessKey It is used to set keyboard shortcut for the control.

TabIndex The tab order of the control.

BackColor It is used to set background color of the control.

BorderColor It is used to set border color of the control.


BorderWidth It is used to set width of border of the control.

Font It is used to set font for the control text.

ForeColor It is used to set color of the control text.

Text It is used to set text to be shown for the control.

ToolTip It displays the text when mouse is over the control.

Visible To set visibility of control on the form.

Height It is used to set height of the control.

Width It is used to set width of the control.

NextMonth Text It is used to set text for the next month button.

TitleFormat It sets format for month title in header.

DayHeaderStyle It is used to set style for the day header row.

DayStyle It is used to apply style to days.

NextPrevStyle It is used to apply style to the month navigation buttons.

Calendar Property Window

Example

In this example, we are implementing calendar and displaying user


selected date to the web page.

// WebControls.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebControls.aspx.cs"


Inherits="WebFormsControlls.WebControls" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<h2>Select Date from the Calender</h2>
<div>
<asp:Calendar ID="Calendar1" runat="server"
OnSelectionChanged="Calendar1_SelectionChanged"></asp:Calendar>
</div>
</form>
<p>
<asp:Label runat="server" ID="ShowDate" ></asp:Label>
</p>
</body>
</html>

Code Behind

// WebControls.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormsControlls
{
public partial class WebControls : System.Web.UI.Page
{
public void Calendar1_SelectionChanged(object sender, EventArgs e)
{
ShowDate.Text = "You Selected: "+Calendar1.SelectedDate.ToString("D");
}
}
}

Output:

This view shows calendar to the browser.

It shows date selected by the user at the web page. A screenshot is


attached below.
List box
A Listbox is used to showcase a list of items on the Web form. Let's see how we can implement this with an
example shown below. We will add a list box to the form to store some city locations.

Step 1) The first step is to drag the list box control on to the Web Form from the toolbox as shown below

Step 2) Once you drag the listbox to the form, a separate side menu will appear. In this menu choose the 'Edit Items'
menu.

Step 3) You will now be presented with a dialog box in which you can add the list items to the listbox.

1. Click on the Add button to add a list item.


2. Give a name for the text value of the list item – In our case Mumbai. Repeat steps 1 and 2 to add list items
for Mangalore and Hyderabad.
3. Click on the OK button
Step 4) Go to the properties window and change the ID property value of the control to lstLocation.

Once you make the above changes, you will see the following output

Output:-

From the output, you can clearly see that the Listboxes was added to the form.
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.

EnableClientScript 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.

MinimumValue It specifies the minimum value of the range.

MaximumValue It specifies the maximum value of the range.

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">

</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.

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">

</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 Escapes 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.
Metacharacters 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:

The content file code is as given:


<form id="form1" runat="server">

<table style="width: 66%;">


<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 Session
In ASP.NET session is a state that is used to store and retrieve values of a user.

It helps to identify requests from the same browser during a time period (session). It is used to store value for the
particular time session. By default, ASP.NET session state is enabled for all ASP.NET applications.

Each created session is stored in SessionStateItemCollection object. We can get current session value by
using Session property of Page object. Let's see an example, how to create an access session in asp.net application.

ASP.NET Session Example

In the following example, we are creating a session and storing user email. This example contains the following files.

// Default.aspx
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="SessionExample._Default" %>
<head>
<style type="text/css">
.auto-style1 {
width: 100%;
}
.auto-style2 {
width: 105px;
}
</style>
</head>
<form id="form1" runat="server">
<p>Provide Following Details</p>
<table class="auto-style1">
<tr>
<td class="auto-style2">Email</td>
<td>
<asp:TextBox ID="email" runat="server" TextMode="Email"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2">Password</td>
<td>
<asp:TextBox ID="password" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style2"> </td>
<td>
<asp:Button ID="login" runat="server" Text="Login" OnClick="login_Click" />
</td>
</tr>
</table>
<br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<br />
<asp:Label ID="Label4" runat="server"></asp:Label>
</form>

Code

// Default.aspx.cs
using System;
using System.Web.UI;
namespace SessionExample
{
public partial class _Default : Page
{
protected void login_Click(object sender, EventArgs e)
{
if (password.Text=="qwe123")
{
// Storing email to Session variable
Session["email"] = email.Text;
}
// Checking Session variable is not empty
if (Session["email"] != null)
{
// Displaying stored email
Label3.Text = "This email is stored to the session.";
Label4.Text = Session["email"].ToString();
}
}
}
}

Output:

This application will store user email to the session when user
login.

It will show stored session value, user email.

State Management System in ASP.NET


Maintaining state is an important part of any web application. State Management System is a mechanism to track the
user state, or data, which is significant with particular application. State management manages the state of an object
on different request.
The HTTP protocol is the fundamental protocol of the World Wide Web. HTTP is a stateless protocol means every
request is from new user with respect to web server. HTTP protocol does not provide any method of determining
whether any two requests are made by the same person.

There are two types of state management system in ASP.NET.

 Client-side state management


 Server-side state management
Client-side state management stores information on the client’s computer and server-side state management stores
the information in the server’s memory or a database.

Client side state management system

ASP.NET provides several techniques for storing state information on the client. These include the following:

 View state: ASP.NET uses view state to track values in controls between page requests. It works within the page
only. You cannot use view state value in next page. ASP.NET page contains a hidden form field named
__VIEWSTATE. This hidden form field stores the value of the control’s property. When the page is posted back to
the server, then the value of __VIEWSTATE is pulled out and re-creates the values of all the properties stored in
View State.

 Control state: The data that is associated with the server controls is called as control state. You can persist
information about a control that is not part of the view state. If view state is disabled for a control or the page, the
control state will still work.

 Hidden fields: It store data without displaying that control and data to the user’s browser. This data is presented
back to the server and is available when the form is processed. Hidden fields data is available within the page only
(page-scoped data). It is rendered as an <input type= "hidden"/> HTML tag. Hidden field should not be used to
store confidential data.

 Cookies: Cookies are small piece of information that server creates on the browser. Cookies store a value in the
user’s browser that the browser sends with every page request to the web server. It works on key/value pair.

There are two types of cookies:

 Session cookies
 Persistent cookies
 Query strings: In query strings values are stored at the end of the URL. These values are visible to the user through
his or her browser’s address bar. Query strings are not secure. You should not send secret information through the
query string.
View state
View state is an inbuilt feature of ASP.NET that retains values between multiple requests for the same page.
ASP.NET page contains a hidden form field named __VIEWSTATE. This hidden form field stores the value of the
control’s property. By default view state is enabled for page and its controls. You can disable view state by setting
the property EnableViewState as false. Storing too much data into View State can hamper the performance of web
page.
Therefore we should take care while enabling and disabling the property EnableViewState.

Example

//writing information to view state


ViewState.Add("MyInfo", "Welcome");
//read information from view state
if (ViewState["MyInfo"] != null)
{
string data = (string)ViewState["MyInfo"];
}

Hidden fields
Hidden fields in HTML are simply input fields and not visible on the browser during execution. Hidden fields are
used to store data at the page level. Hidden fields are simple to implement for a page specific data and stores small
amount of data. We should not use hidden fields for sensitive data. It has no built-in compression, encryption
technique.

<asp:HiddenField ID="HiddenField1" runat="server" />

Example

//writing information to Hidden field


HiddenField1.Value = "Welcome";
//read information from Hidden field
string str = HiddenField1.Value;

Cookies
A cookie is a small amount of data that server creates on the client. Cookie is small text information. You can store
only string values when using a cookie. When a request sent to web server, server creates a cookie, and sent to
browser with an additional HTTP header.

The HTTP header looks like this:

Set-Cookie: message=Hello.

Here cookie name is message and value is hello.

If the cookies has created on a browser and user requests a page from the same application, then the browser sends a
header that looks like this:

Cookie: message=Hello
There are two types of cookies:

 Session cookies
 Persistent cookies
A session cookie exists only till the user closes the web browser, the session cookie deleted permanently.

A persistent cookie, on the other hand, can available for months or even years. When you create a persistent cookie,
the cookie is stored permanently by the user’s browser on the user’s computer.

Use of Cookies
Some common uses of cookies are:

 Authentication of user.
 Identification of a user session.
 User's preferences.
 Shopping cart contents.
 Remember users between visits.
Creating and reading cookies
We can create cookies in different ways.

Example 1

Response.Cookies["Message"].Value = TextBox1.Text;
string msg = Request.Cookies["Message"].Value;

Example 2

HttpCookie UserCookies = new HttpCookie("Message");


UserCookies.Value = TextBox1.Text;
Response.Cookies.Add(UserCookies);
// Reading the cookie.
string roll = Request.Cookies["Message"].Value;

Example 3

//Writing Multiple values in single cookie


Response.Cookies["EmpCookies"]["EmpID"] = txtID.Text;
Response.Cookies["EmpCookies"]["FirstName"] = txtFirstName.Text;
Response.Cookies["EmpCookies"]["LastName"] = txtLastName.Text;
Response.Cookies["EmpCookies"]["Address"] = txtAddress.Text;

//Reading Cookie.
string info;
if (Request.Cookies["EmpCookies"] != null)
{
info = Request.Cookies["EmpCookies"]["EmpID"] + "</br>";
info += Request.Cookies["EmpCookies"]["FirstName"] + "</br>";
info += Request.Cookies["EmpCookies"]["LastName"] + "</br>";
info += Request.Cookies["EmpCookies"]["Address"] + "</br>";

Label1.Text = info;
}
// cookie names are case sensitive. Cookie named EmpCookies is different from setting a cookie named empcookies.

The above examples create a session cookie. The cookie disappears when you close your web browser. If you want
to create a persistent cookie, then you need to specify an expiration date for the cookie.

Response.Cookies["message"].Expires = DateTime.Now.AddYears(1);

Limitaion of cookies

 Cookie can store only string value.


 Cookies are browser dependent.
 Cookies are not secure.
 Cookies can store small amount of data.
 Size of cookies is limited to 4096 bytes.
Important properties of HttpCookie

 Domain: Enables you to get or set the domain of the cookie.


 Expires: It contains the expiration time of the cookie.
 HasKeys: Returns bool value, indicating whether the cookie has subkeys.
 Name: Provides the name of the cookie.
 Path: Enables you to get or set the virtual path to submit with the cookie.
 Secure: It contains true if the cookie is to be passed with SSL.
 Value: It contains the value of the cookie.
Example

using System;
using System.Web;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie obj = new HttpCookie("MyCookie");
obj.Value="Welcome !!";
Response.Cookies.Add(obj);
string info;
info = "Domain =: " + obj.Domain + "</br>";
info += "Name =: " + obj.Name + "</br>";
info += "Path =: " + obj.Path+"</br>";
info += "Value =: " + obj.Value + "</br>";
info += "HasKeys =: " + obj.HasKeys + "</br>";
info += "Secure =: " + obj.Secure + "</br>";
Label1.Text = info;
}
}

Query strings

Query String object is helpful when we want to transfer a value from one page to another. Query String is very easy
to use. Query string values are appended to the end of the page URL. It uses a question mark (?), followed by the
parameter name followed by an equal sign (=) and its value. You can append multiple query string parameters using
the ampersand (&) sign.

Always remember, we should not send lots of data through QueryString. Another limitation is that information we
send through QueryString is visible on the address bar.

Example:

Response.Redirect("Default.aspx?msg="+txtMessage.Text);

In the example, the Response.Redirect method requests the Default.aspx page. The query string contains a single
parameter named msg. The value for that parameter is set at run time by entering the data into textbox control. In
this example the query string has one parameter but we can pass more than one parameter as given below.

Response.Redirect("Default2.aspx?ID=" + txtID.Text + "&Name=" + txtFirstName.Text);

Reading values from QueryString

Label1.Text = "ID: " + Server.HtmlEncode(Request.QueryString["ID"]) + ", Name: " +


Server.HtmlEncode(Request.QueryString["Name"]);

We should use Server.HtmlEncode method while using QueryString. Server.HtmlEncode method encode the "<"
sign with "<." Special characters that a Web browser cannot process, it helps to process that browser understands
easily.

Important points about QueryString

It is easy to use.

 Sensitive data should not pass using QueryString.


 Browsers have 2,083-character limits on URLs. Therefore there is limit to pass the data.
 QueryString is a part of URL.
 It uses one or more than one parameter.
 It uses "&" sign while using more than one parameter.
 SPACE is encoded as '+' or '%20'

You might also like