0% found this document useful (0 votes)
26 views26 pages

Unit Ii

Unit II of the ASP.NET course covers form validation, including client-side and server-side validation techniques, and various validation controls such as RequiredFieldValidator, RangeValidator, and CompareValidator. It explains the importance of ensuring correct data input through validation controls and provides examples of how to implement these controls in a web form. Additionally, it discusses state management techniques and the use of ValidationSummary and CustomValidator for handling validation errors effectively.

Uploaded by

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

Unit Ii

Unit II of the ASP.NET course covers form validation, including client-side and server-side validation techniques, and various validation controls such as RequiredFieldValidator, RangeValidator, and CompareValidator. It explains the importance of ensuring correct data input through validation controls and provides examples of how to implement these controls in a web form. Additionally, it discusses state management techniques and the use of ValidationSummary and CustomValidator for handling validation errors effectively.

Uploaded by

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

22UBCAC62: ASP.

NET UNIT 2

UNIT II: FORM


Hours:15
Form validation: Client side validation, Server side validation, Validation
Controls: Required Field Comparison Range, Calendar Control, Ad rotator
Control, Internet Explorer Control. State Management: View State, Control State,
Hidden Fields, Cookies, Query Strings, Application State, Session State.
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
1 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

3. CompareValidator
4. RegularExpressionValidator
5. CustomeValidator
6. ValidationSummary
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">
2 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

<div> Your
Name
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1"
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.
3 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

Example:

<%@ 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.

4 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

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.
- 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"
5 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

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.

<%@ 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>
6 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

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

7 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

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

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


<html>
<head><title>Untitled Page</title></head>
<body>
<form id="form1" runat="server">
<div>
8 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

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.

9 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

<%@ 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 />
10 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

Your Email ID
<asp:TextBox ID="TextBox4" runat="server"/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
runat="server" ControlToValidate="TextBox4"
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.

11 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

<%@ 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>
Basics of Regular expression

d (for digits)
w (for character)
{n} (n is exact number of allowed digits or character) [a-z](match any
12 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

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})

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:

13 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

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

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


<script runat="server">
void Button1_Click(object sender, EventArgs e)
{
BulletedList1.DataSource = Calendar1.SelectedDates;
BulletedList1.DataBind();
}
</script>

<html>
14 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

<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.
15 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

Events:

- AdCreated: Raised after the AdRotator control selects an advertisement


but before the AdRotator control renders the advertisement.
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 Item🡪add 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"
16 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

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

17 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

<asp:MenuItem Text="Service2" NavigateUrl="~/s2.aspx" />


</asp:MenuItem>
</Items>
</asp:Menu>
</div>
</form>
</body>
</html>
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)
{
18 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

if (ViewState["count"] == null)
{
ViewState["count"] = "1";
}
else
{
int i = Convert.ToInt32(ViewState["count"]) + 1; ViewState["count"]
= i.ToString();
}
}
}
</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>

19 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

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
}
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

20 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

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>
</form>
</body>
</html>

4. nextpage.aspx
21 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

<%@ 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
}

22 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

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>

23 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

<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" />
</div>
</form>
</body>
</html>

CONTROL STATE, HIDDEN FIELDS, COOKIES, QUERY STRINGS IN


ASP.NET

In ASP.NET, managing state between requests and passing data between different
parts of the application is a crucial part of web development. Various techniques are
available for storing data on the client and server side. Here’s a breakdown of Control
State, Hidden Fields, Cookies, and Query Strings in ASP.NET:
1. Control State
Control state in ASP.NET is used to store data specific to a control that must persist
across postbacks, similar to the ViewState, but it is more reliable in certain scenarios
because it is not turned off, even if the EnableViewState property of a control is set to
false.
 Use Cases: Storing data that is critical to the control’s operation (e.g., a custom
control).
 Key Characteristics:
o It persists across postbacks.
o It is stored in the page’s hidden section like ViewState, but it cannot be
disabled.
o Data in the control state is not accessible by the user unless they have
access to the page’s source code.
How to use:
 You can store data in the control state by overriding the SaveControlState() and
LoadControlState() methods of a custom control.
csharp
Copy code
public class MyCustomControl : WebControl
{
private string myControlData;
24 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK
22UBCAC62: ASP.NET UNIT 2

protected override object SaveControlState()


{
return myControlData;
}

protected override void LoadControlState(object savedState)


{
if (savedState != null)
{
myControlData = (string)savedState;
}
}
}
2. Hidden Fields
Hidden fields in ASP.NET are used to store data in a page that will not be visible to
the user but will persist across requests. The data is stored in the HTML form, and it
can be accessed on the server side.
 Use Cases: Storing form values that should not be modified or visible but need to
be submitted with the form (e.g., user session ID, product details).
 Key Characteristics:
o Hidden fields are part of the HTML page and are sent with each form
submission.
o They are visible in the page’s source code but not rendered to the user.
How to use: You can use the HiddenField control in ASP.NET to store data.
html
Copy code
<asp:HiddenField ID="HiddenField1" runat="server" Value="SomeValue" />
On the server side, you can access the value like this:
csharp
Copy code
string hiddenValue = HiddenField1.Value;
3. Cookies
Cookies are small pieces of data that the server sends to the client’s browser, and they
are stored on the client’s machine. Cookies can be used to persist data between user
sessions and across multiple requests.
 Use Cases: Storing user preferences, login information, or tracking user activities
across sessions.
 Key Characteristics:
o Cookies are sent with every request to the server for the domain.

25 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK


22UBCAC62: ASP.NET UNIT 2

o They are stored on the client-side, meaning users can modify or delete
them.
o Cookies can be persistent (stay across sessions) or session cookies (only
for the duration of the browser session).
How to use: Creating and retrieving cookies in ASP.NET:
csharp
Copy code
// Creating a cookie
HttpCookie cookie = new HttpCookie("UserPreferences");
cookie["Theme"] = "Dark";
cookie.Expires = DateTime.Now.AddDays(7); // Persist for 7 days
Response.Cookies.Add(cookie);

// Retrieving a cookie
HttpCookie retrievedCookie = Request.Cookies["UserPreferences"];
if (retrievedCookie != null)
{
string theme = retrievedCookie["Theme"];
}
4. Query Strings
Query strings are parts of the URL that can be used to pass information between
pages. They are visible to the user and can be modified in the browser's address bar.
 Use Cases: Passing data in the URL, such as page number in a paginated list,
search terms, or user identifiers.
 Key Characteristics:
o Data is visible to the user.
o It has a length limitation (varies by browser, typically around 2048
characters).
o It is often used for GET requests, where the parameters are appended to the
URL.

26 DEPARTMENT OF COMPUTER SCIENCE-Mrs. SUGANYA, AP/RAAK

You might also like