0% found this document useful (0 votes)
151 views23 pages

WT ASP - Net Unit IV Notes

The document discusses form validation in ASP.NET, including client-side validation, server-side validation, and different validation controls. It provides examples of using the RequiredFieldValidator, RangeValidator, and CompareValidator controls to validate form fields. Validation controls can validate that a field is required, that a value is within a specified range, or that two fields contain matching values. Both client-side and server-side validation are supported.

Uploaded by

Jayshree Borkar
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)
151 views23 pages

WT ASP - Net Unit IV Notes

The document discusses form validation in ASP.NET, including client-side validation, server-side validation, and different validation controls. It provides examples of using the RequiredFieldValidator, RangeValidator, and CompareValidator controls to validate form fields. Validation controls can validate that a field is required, that a value is within a specified range, or that two fields contain matching values. Both client-side and server-side validation are supported.

Uploaded by

Jayshree Borkar
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/ 23

ASP.

NET Notes
UNIT-II
Form Validation:
Client side validation
Server Side validation
Validation Controls:
Required Field
Comparison
Range
Regular Expression
Summary
Custom
Calendar control
Ad rotator Control
Internet Explorer Control
State management:
View state
Session state
Application state,

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 27
ASP.NET Notes
Form Validation:
A web form has many input controls like TextBoxs. These controls should
have right type of data before submitting form at server side for data
processing. Thus checking the input controls called form validation.
Form validation includes-
1. Check control has required value.
2. Check value of control falls between minimum and maximum value.
3. Compare value of control against another value.
4. Check value of control is match with given format.
For example: If data is not input into TextBox then an error message should
be display. It is done using RequiredFieldValidator control.

Client side and server side Validation:


The validation of control can be performed at client side and server side.
1. Client side validation: When validation code is executed at client side
by Browser software called client side validation. Client side validation
prevents form submission to the server until all input values of control
becomes error less. Validation code is written / generated in JScript for
client side validation. Client side validation saves time for checking error
that may consumes in between client to server and server to client.

2. Server side validation: When validation code is executed at server side


by any programming language (C# / VB) called server side validation.
Server side validation happens after form submission to the server. At
server side, values of controls are checked. If any error founds then
response to the client side using new web page. This process consumes
more time as compared to client side validation.

Validation Controls:
ASP.NET provides following set of validation controls that may validate
value of form control at client side (default) or server side.
1. RequiredFieldValidator
2. RangeValidator
3. CompareValidator
4. RegularExpressionValidator
5. CustomeValidator
6. ValidationSummary

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 28
ASP.NET Notes
These validation controls can be apply on any control that has decorated
with ValidationProperty attribute.

RequiredFieldValidator control:

This validation control checks to required value is input or not into specified
input control before submitting the form. This control needs to link any one
input control like TextBox.
Syntax:
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ToolTip: The tooltip displayed when the mouse is over the control.
- EnableClientScript: If it is true then validation is performed at client
side by browser otherwise performed at server side.

CauseValidation property of Button: If false then button does not causes


validation to fire.
Example:

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


<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Your Name
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="TextBox1"

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 29
ASP.NET Notes
ErrorMessage="Your Name is empty"
ToolTip="Input Your Name"
Text="(Required)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button2" runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>

RangeValidator control:

This validation control checks input value falls between a certain minimum
and maximum value. This control needs to link any one input control like
TextBox.
Syntax:
<asp:RangeValidator ID="RangeValidator1" runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- MinimumValue: The minimum value for the control being validated.
- MaximumValue: The maximum value for the control being
validated.
- Type: Data type of values for comparison. (String / Integer / Double /
Date / Currency)
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ToolTip: The tooltip displayed when the mouse is over the control.
- EnableClientScript: If it is true then validation is performed at client
side by browser otherwise performed at server side.

CauseValidation property of Button: If false then button does not causes


validation to fire.
Example:

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 30
ASP.NET Notes
<%@ Page Language="C#" %>
<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Your Age
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1"
Type="Integer"
MinimumValue="18"
MaximumValue="60"
Text="(Out of 18-60)"
ToolTip="Input value between 18-60"
ErrorMessage="Out of range(18-60)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button2" runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>

CompareValidator control:

This validation control performs three type of validation.


1. Check data type of value.
2. Compare input value against fixed value.
3. Compare input value against another input value.
Syntax:
<asp:CompareValidator ID="CompareValidator1"
runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- ControlToCompare: ID of the control to compare with.
- Type: Data type of values for comparison. (String / Integer / Double /
Date / Currency)
- Operator: Comparison operation to apply to value. (Equal /
NotEqual / GreaterThan / …)
- ValueToCompare: The fixed value to compare against.
Author: Mr. Lokesh Rathore (MCA, MTech)
WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 31
ASP.NET Notes
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ToolTip: The tooltip displayed when the mouse is over the control.
- EnableClientScript: If it is true then validation is performed at client
side by browser otherwise performed at server side.

CauseValidation property of Button: If false then button does not causes


validation to fire.
Example1: Check data type.

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


<html>
<head><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Date of Birth
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:CompareValidator ID="CompareValidator1"
runat="server" ControlToValidate="TextBox1"
Operator="DataTypeCheck"
Type="Date"
Text="(Invalid (mm/dd/yyyy)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>
Example2: Check input integer value is more than 18.

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 32
ASP.NET Notes
<%@ Page Language="C#" %>
<html>
<head><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Your age
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ControlToValidate="TextBox1"
Operator="GreaterThan"
Type="Integer"
ValueToCompare="18"
Text="(Input more than18)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>
Example3: Compare input password to confirm password.

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


<html>
<head><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Your password
<asp:TextBox ID="TextBox1" runat="server"
TextMode="Password" />
<br />
Confirm Password
<asp:TextBox ID="TextBox2" runat="server"
TextMode="Password" />
<asp:CompareValidator ID="CompareValidator1"
runat="server" ControlToCompare="TextBox1"
ControlToValidate="TextBox2"
Type="String"

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 33
ASP.NET Notes
Operator="Equal"
Text="(Password Not matched)" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>

RegularExpressionValidator control:

This validation control compares input value against a regular expression.


We can use a regular expression to represent string pattern such as email
address, dates etc.
Syntax:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- ValidationExpression:The Regular expression is assigned to this
property. (http://regexlib.com for all list)
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ToolTip: The tooltip displayed when the mouse is over the control.
- EnableClientScript: If it is true then validation is performed at client
side by browser otherwise performed at server side.

CauseValidation property of Button: If false then button does not causes


validation to fire.
Example: Check valid EmailID format

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 34
ASP.NET Notes
<%@ Page Language="C#" %>
<html>
<head><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Your Email ID
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationExpression=
"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Text="(Invalid EmailID format" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
<asp:Button ID="Button runat="server" Text="Cancel"
CausesValidation="False" />
</div>
</form>
</body>
</html>

ValidationSummary control:

This control display a list of all validation errors which are given in
ErrorMessage of each validation control.
Syntax:
<asp:ValidationSummary ID=" ValidationSummary1"
runat="server" />
Important Properties:
- DisplayMode: Format for error summary display. (BulletList /
SingleParaGraph / List)
- HeaderText: To display header text on the top of summary control.
- ShowMessageBox: True means display a popup alert box.
- ShowSummary: False then summary hides.

CauseValidation property of Button: If false then button does not causes


validation to fire.
Example: Show summary of validation of all validation controls.

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 35
ASP.NET Notes

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


<html>
<head>
<title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:ValidationSummary ID="ValidationSummary1"
runat="server" />
<br />
Your Name
<asp:TextBox ID="TextBox1" runat="server"/>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="Input your Name"
Text="*" />
<br />
Your age
<asp:TextBox ID="TextBox2" runat="server" />
<asp:RangeValidator ID="RangeValidator1"
runat="server" ControlToValidate="TextBox2"
ErrorMessage="Input age 18-60"
MaximumValue="60" MinimumValue="18"
Type="Integer" Text="*" />
<br />
Your Birth Date
<asp:TextBox ID="TextBox3" runat="server" />
<asp:CompareValidator ID="CompareValidator1"
runat="server"
ControlToValidate="TextBox3"
ErrorMessage="Invalid date format"
Operator="DataTypeCheck"
Type="Date" Text="*" />
<br />
Your Email ID
<asp:TextBox ID="TextBox4" runat="server"/>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox4"
Author: Mr. Lokesh Rathore (MCA, MTech)
WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 36
ASP.NET Notes
ErrorMessage="Invalid Email ID Format"
ValidationExpression=
"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
Text="*" />
<br />
<asp:Button ID="Button1" runat="server"
Text="Submit" />
<asp:Button ID="Button2" runat="server"
Text="Cancel" CausesValidation="False" />
</div>
</form>
</body>
</html>

CustomValidator control:

If none of the other validation controls perform the type of validation that
we need then we can use CustomValidator control. In this control, we can
associate function for a custom validation.
Syntax:
<asp:CustomValidator ID="CustomValidator1"
runat="server" />
Important Properties:
- ControlToValidate: ID of control to be validate.
- Text: text to display for the validator when the validated control is
invalid.
- ErrorMessage: Message to display in a ValidationSummary when
the validated control is invalid.
- ServerValidate(Event): This event raised when the CustomValidator
performs validation.

CauseValidation property of Button: If false then button does not causes


validation to fire.

Example: Check input string length is greater than 10.

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 37
ASP.NET Notes
<%@ Page Language="C#" %>
<script runat="server">
void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (args.Value.Length <= 10)
args.IsValid = true;
else
args.IsValid = false;
}
</script>

<html>
<head><title>Custome Validation Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Input string of 10 character
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ControlToValidate="TextBox1"
OnServerValidate="CustomValidator1_ServerValidate"
Text="(String Length is greater than 10) />
<br />
<asp:Button ID="Button1" runat="server"
Text="Submit" />
</div>
</form>
</body>
</html>

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 38
ASP.NET Notes
Basics of Regular expression
d (for digits)
w (for character)
{n} (n is exact number of allowed digits or character)
[a-z](match any one specified character)
+ (for one or more d/w)
\ (flow of d/w)

for example:

\d{1} to allow only one digits ex: 0 to 9


\d{5} to allow only 5 digits ex:00000 to 99999
\w{6} to allow only 6 character ex: lokesh, ujjain, p-1234
\d+ to allow one or more digits ex: 1, 21, 345 5444
\w+ to allow one or more digits ex: l, lo, lok5444

d{4}(-d{5}) to allow 4 digits - 5 digits (3234-32434)

***for one character**


[a]
[ad]
[a-z]
[A-Z]
[0-9]
[-+*/]

***one or more ***


digits(233) : \d+
Small Alphabet(lokesh) : [a-z]+
Capital Alphabet(lokesh) : [A-Z]+
digits with one . dot(233.23) : \d+(.\d+)
***fix number of ***
5 digits(233) : \d{5}
5Small Alphabet(lokesh) : [a-z]{5}
(5,2)digits with one . dot(233.23) : \d{5}(.\d{2})

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 39
ASP.NET Notes
Calendar control:

The Calendar control displays a calendar that can use as a date picker or to
display a list of upcoming events.

Syntax:
<asp:Calendar ID="Calendar1" runat="server"/ >
Properties:
- Caption: The caption associated with calender.
- DayNameFormat: To set day name as(Mon/Monday/Mo/M.
- FirstDayOfWeek:Which day of week display first. (Sun/Mon/Tue..).
- NextMonthText: To set text for next month Button.(&gt for >).
- PrevMonthText: To set text for previous month Button. (&lt for <).
- NextPrevFormat: To set format for Next and Previous month
navigation buttons.(ShortMonth / FullMonth/ CustomText).
- SelectedDate: To get or set selected date.
- SelectedDates: To get multiple dates(C#).
- ShowDayHeader: If false then dayname becomes hides.
- ShowNextPrevMonth: If false then next and previous month hides.
- ShowTitle: If false then title of calender hides.
- TitleFormat: Set Month or Month Year.
- VisibleDate: Set the month of calender.
- SelectionMode: To set selection day/week/month.

Events:
- DayRender: Raised as each day is rendered.
- SelectionChanged: Raised when a new day, week, or month is
selected.
- VisibleMonthChanged: Raised when the next or previous month link
is clicked.

Example: Show all dates of selected week in a bullet list control.

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 40
ASP.NET Notes
<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(object sender, EventArgs e)
{
BulletedList1.DataSource = Calendar1.SelectedDates;
BulletedList1.DataBind();
}
</script>

<html>
<head><title>Get Selected Dates Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Calendar ID="Calendar1" runat="server"
SelectionMode="DayWeekMonth"></asp:Calendar>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Submit" />
<asp:BulletedList ID="BulletedList1" runat="server"
DataTextFormatString="{0:d}"></asp:BulletedList>
</div>
</form>
</body>
</html>

AdRotator control:

The AdRotator control is used to randomly display images of different


advertisements in a page. List of advertisements can be stored in an XML
file or in a database table.
Syntax:
<asp:AdRotator ID="AdRotator1" runat="server" />
Properties:
- AdvertisementFile: To specify path of XML file containing
advertisements.
- AlternateTextField: The element name (AlternateText) that specify
which alternate text to retrieve.
- ImageUrlField: The element name (ImageUrl) that specify which
image URL to retrieve.
- NavigateUrlField: The element name (NavigateUrl) that specify which
advertisement web page URL to retrieve.
Events:
- AdCreated: Raised after the AdRotator control selects an
advertisement but before the AdRotator control renders the
advertisement.
Author: Mr. Lokesh Rathore (MCA, MTech)
WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 41
ASP.NET Notes
Procedure to add advertisements on AdRotator control using XML file.

1) Add AdRotator control on web page. (AdRotator1)


2) Create AdImage folder in root folder of website.
3) Copy Ad Images into AdImage folder.(let ad1.jpg, ad2.jpg)
4) Open an XML: Add New Itemadd XML file(adXML.xml)
5) Write following XML code to add list of ad images.
<Advertisements>
<Ad>
<ImageUrl>~/AdImage/Ad1.jpg</ImageUrl>
<AlternateText>LRsir</AlternateText>
<NavigateUrl>http://www.LRsir.net</NavigateUrl>
<Impressions>50</Impressions>
<Keyword>banner</Keyword>
<Width>400</Width>
<Height>200</Height>
</Ad>

<Ad>
<ImageUrl>~/AdImage/Ad2.jpg</ImageUrl>
<AlternateText>Advance College</AlternateText>
<NavigateUrl>www.advcol.com</NavigateUrl>
<Impressions>20</Impressions>
<Keyword>banner</Keyword>
<Width>400</Width>
<Height>200</Height>
</Ad>
</Advertisements>
6) Attach adXML.xml file to AdvertisementFile property and add
Keyword value to KeywordFilter property.
<asp:AdRotator ID="AdRotator1" runat="server"
KeywordFilter="banner"
AdvertisementFile="~/AdXMLFile.xml" />

When web page is refreshed then Ad images replaced by another Ad


images. Number of occurrence of any advertisement depends upon
impressions value.

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 42
ASP.NET Notes
Menu control: Internet Explorer Control

This control is used to create vertical and horizontal list of link in drop
down menu format.
Syntax:
<asp:Menu ID="Menu1" runat="server"/>
Properties:
- Orientation: To set Vertical / Horizontal menu.
- Items: To add collection of links.

Example: Create Horizontal menu.

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


<html>
<head><title>Explorer Control Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu ID="Menu1" runat="server"
Orientation="Horizontal">
<Items>
<asp:MenuItem Text="Home"
NavigateUrl="~/default.aspx" />
<asp:MenuItem Text="Product">
<asp:MenuItem Text="Product1"
NavigateUrl="~/p1.aspx" />
<asp:MenuItem Text="Product2"
NavigateUrl="~/p2.aspx" />
</asp:MenuItem>
<asp:MenuItem Text="Services">
<asp:MenuItem Text="Service1"
NavigateUrl="~/s1.aspx" />
<asp:MenuItem Text="Service2"
NavigateUrl="~/s2.aspx" />
</asp:MenuItem>
</Items>
</asp:Menu>
</div>
</form>
</body>
</html>

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 43
ASP.NET Notes
ASP.NET State Management:
When user request same page or different page then server cleans up all the
created variable and object after serving that page to the user. State
management is the process by which we store information between multiple
requests for the same page or different pages.

In ASP.NET, We can use following three type of state management system.


1) ViewState
2) Session
3) Application
ViewState:
It is a client side page level state management technique i.e. as long as the
user is on the current page, state is available and when user redirect to the
next page then state is lost.
It is used when user needs to preserve data temporarily after a post back
then the ViewState stores data in the generated HTML using hidden field.
View State can store any type of data because it is object type. View state is
enabled by default for all ASP.NET controls.
Syntax: ViewState["Variable_Name"]
We can create a number of ViewState variables.
Example: Count number of button's click
<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(object sender, EventArgs e)
{
Label1.Text = ViewState["count"].ToString();
}
void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState["count"] == null)
{
ViewState["count"] = "1";
}
else
{
int i = Convert.ToInt32(ViewState["count"]) + 1;
ViewState["count"] = i.ToString();
}
}
}
Author: Mr. Lokesh Rathore (MCA, MTech)
WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 44
ASP.NET Notes
</script>

<html>
<head><title>ViewState Page</title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="ok"
OnClick="Button1_Click" />
</div>
</form>
</body>
</html>

Session:
It is a server side state management technique i.e. as long as the user is on
current page or next page, state is always available and when user idles up
to specified session time then session state lost. The server maintains the
state of user information by using a session ID.
When user makes a request without a session ID, ASP.NET creates a
session ID and sends it with every request and response to the same user.
Syntax: Session["Variable_Name"]

Session Events: We can executes codes when session starts or end using
Session_Start and Session_End events. Session events are defining
in Global.asax file that creates into root folder of website.
void Session_Start(object sender, EventArgs e)
{
// Write code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Write code that runs when a active session is expired
}

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 45
ASP.NET Notes
The Session_End event is raised when session ends either because of a time
out expiry or explicitly by using Session.Abandon().
Set Session Time: Add <sessionState> into web.config file of root folder.
<configuration>
<system.web>
<sessionState timeout="10" mode="InProc" />
</system.web>
</configuration>
The Session_End event is raised only in the case of InProc mode not in
the state server and SQL Server modes.
Example: Assign name into one page and display into next page. Set 1
minute for session time.

1. Global.aspx
void Session_Start(object sender, EventArgs e)
{
Session["username"] = "none";
}
2. web.config
<sessionState timeout="10" mode="InProc" />
3. session.aspx
<%@ Page Language="C#" %>
<script runat="server">
Button1_Click(object sender, EventArgs e)
{
Session["username"] = TextBox1.Text;
Response.Redirect("~/nextPage.aspx");
}
</script>
<html>
<head><title>Session Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Input Name
<asp:TextBox ID="TextBox1" runat="server" />
<asp:Button ID="Button1" runat="server"
Text="Submit" OnClick="Button1_Click" />
</div>

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 46
ASP.NET Notes
</form>
</body>
</html>

4. nextpage.aspx
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["username"].ToString();
}
</script>

<html>
<head><title>Next Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" />
</div>
</form>
</body>
</html>

Application:
Application state is a server side state management technique. The data
stored in application state is common for all users of that particular
ASP.NET application and can be accessed anywhere in the application. It is
also called application level state management. Data stored in the
application should be of small size.
Syntax: Application["Variable_Name"]

Application Events:

Application events are defining in Global.asax file that creates into root
folder of website.

Application_Start: It is raised when the first request is made using


domain(www.LRsir.net) of web site.
void Application_Start(object sender, EventArgs e)
{
// Write code
}

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 47
ASP.NET Notes
Application_End: It is raised just before the domain ends, server
restart, when the first request is made using domain(www.LRsir.net) of web
site.
void Application_End(object sender, EventArgs e)
{
// Write code
}

Application_Error: It is raised when an exception is occurs then it


can be handles using this event.
void Application_Error(object sender, EventArgs e)
{
// Write code
}
Example: Count total number of clicks of button by all users.

1. Global.aspx
void Application_Start(object sender, EventArgs e)
{
Application["count"] = 0;
}
2. Application.aspx
<%@ Page Language="C#" %>
<script runat="server">
void Button1_Click(object sender, EventArgs e)
{
int i=Convert.ToInt32(Application["count"]) + 1;
Application["count"] = i.ToString();
Label1.Text = i.ToString();
}
</script>
<html>
<head><title>Application State Page</title></head>
<body>
<form id="form1" runat="server">
<div>
Total clicks by all users
<asp:Label ID="Label1" runat="server"/>
<asp:Button ID="Button1" runat="server"
OnClick="Button1_Click" Text="Submit" />
Author: Mr. Lokesh Rathore (MCA, MTech)
WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 48
ASP.NET Notes
</div>
</form>
</body>
</html>

Author: Mr. Lokesh Rathore (MCA, MTech)


WhatsApp&Call: 9425034034, website: www.LRsir.net, Email: [email protected]
P a g e | 49

You might also like