State Management: Today You Will Learn
State Management: Today You Will Learn
View State
One of the most common ways to store information is in view state.
View state uses a hidden field that ASP.NET automatically inserts in the
final, rendered HTML of a web page.
Example: If you change the text of a label, the Label control
automatically stores its new text in view state. That way, the text
remains In place the next time the page is posted back.
The ViewState Collection
The ViewState property of the page provides the current view state
information.
This property provides an instance of the StateBag collection class.
The StateBag is a dictionary collection, which means every item is
stored in a separate slot using a unique string name.
CSE 409 Advanced Internet Technology
View State
//The this keyword refers to the current Page object. It's optional.
this.ViewState[Counter] = 1;
When retrieving a value, you use the key name. You also need to cast the
retrieved value to the appropriate data type using the casting syntax.
This extra step is required because the ViewState collection stores all items as
basic objects, which allows it to handle many different data types.
int counter;
counter = (int)this.ViewState[Counter];
A View State Example
A simple counter program that records how many times a button is clicked.
View State
public partial class SimpleCounter : Syatem.Web.UI.Page
{
protected void cmdIncrement_Click(object sender, EventArgs e)
{
int counter;
if(ViewState[Counter] == null)
{
counter = 1;
}
else
{
counter = (int)ViewState[Counter] + 1;
}
ViewState[Counter] = counter;
lblCount.Text = Counter : + counter.ToString();
}
}
The code checks to make sure the item exists in view state before it attempts to
retrieve it. Otherwise, you could easily run into problems such as the infamous
null reference exception.
CSE 409 Advanced Internet Technology
View State
Making View State Secure
View state information is stored in a single jumbled string that looks like
this:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="dDw3NDg2NTI5MDg7Oz4=" />
As you add more information to view state, this value can become much
longer. Because this value isnt formatted as clear text.
The view state information is simply patched together in memory and
converted to a Base64 string.
Tamper-Proof View State
There are two choices to make View State more secure:
The view state information is tamperproof by instructing ASP.NET to
use a hash code.
CSE 409 Advanced Internet Technology
View State
A hash code is sometimes described as a cryptographically strong checksum.
Private States: View state contains some information you want to keep secret, you
can enable view state encryption.
o You can turn on encryption for an individual page using the
ViewStateEncryptionMode property of the Page directive:
<%@Page ViewStateEncryptionMode="Always" %>
o you can set the same attribute in a configuration file to configure view state
encryption for all the pages in your website:
<configuration>
<system.web>
<pages viewStateEncryptionMode="Always" />
</system.web>
</configuration>
To convert auto to Always call Page.RegisterRequiresViewStateEncryption()
CSE 409 Advanced Internet Technology
View State
There are three choices for view state encryption settingalways
encrypt (Always), never encrypt (Never), or encrypt only if a control
specifically requests it (Auto).
Retaining Member Variables
The basic principle is to save all member variables to view state when
the Page.PreRender event occurs and retrieve them when the
Page.Load event occurs.
Steps:
o A member variable that will be cleared with every postback.
o If IsPostBack Then Restore variables.
o In Page_PreRender event Persist variables.
CSE 409 Advanced Internet Technology
View State
Disadvantages:
It stores unnecessary information in view state, it will enlarge the size of
the final page output and can thus slow down page transmission times.
It hides the low-level reality that every piece of data must be explicitly
saved and restored.
To use this approach to save member variables in view state, use it
exclusively. That means refrain from saving some view state variables at
the PreRender stage and others in control event handlers.
Storing Custom Objects
To store an item in view state, ASP.NET must be able to convert it into a
stream of bytes so that it can be added to the hidden input field in the
page. This process is called serialization.
CSE 409 Advanced Internet Technology
View State
To make your objects serializable, you need to add a Serializable
attribute before your class declaration.
[Serializable]
10
Cross-Page Posting
A cross-page postback is a technique that extends the postback
mechanism, so that one page can send the user to another page,
complete with all the information for that page.
The infrastructure that supports cross-page postbacks is a property
named PostBackUrl, which is defined by the IButtonControl interface
and turns up in button controls such as ImageButton, LinkButton, and
Button.
CSE 409 Advanced Internet Technology
11
12
The page checks for null reference before attempting to access the
PreviousPage object. If its a null reference, no cross-page postback took
place.
CSE 409 Advanced Internet Technology
13
14
15
16
17
If you try to send query string values that include any of these
characters, youll lose some of your data.
To solve this problem URL encoding on text values before you place
them in the query string.
CSE 409 Advanced Internet Technology
18
19
Cookies
Cookies provide another way that you can store information for later
use.
Cookies are small files that are created in the web browsers memory
(if theyre temporary) or on the clients hard drive.
Advantage:
Cookies work transparently without the user being aware that information needs to be
stored.
Cookies can be easily used by any page in your application and even be retained
between visits, which allows for truly long-term storage.
Disadvantages:
Cookies are limited to simple string information.
Cookies are easily accessible and readable if the user finds and opens the corresponding
file.
CSE 409 Advanced Internet Technology
20
Cookies
Some users disable cookies on their browsers, which will cause
problems for web applications that require them.
Users might manually delete the cookie files stored on their hard drives.
Both the Request and Response objects (which are provided through
Page properties) provide a Cookies collection.
Retrieve cookies from the Request object, and set cookies using the
Response object.
o To set a cookie, just create a new HttpCookie object.
HttpCookie cookie = Request.Cookies[Preference];
Set the value for Cookie
cookie["LanguagePref ] = "English"
o Adding values to the Cookie
cookie["Country] = "US" ;
CSE 409 Advanced Internet Technology
21
Cookies
o Attach Cookie to the current web response
Response.Cookies.Add(cookie);
A cookie added in this way will persist until the user closes the browser
and will be sent with every request.
Creating a longer-lived cookie, by setting an expiration date.
cookie.Expires = DateTime.Now.AddYears(1);
22
Cookies
The only way to remove a cookie is by replacing it with a cookie that has
an expiration date that has already passed.
HttpCookie cookie = new HttpCookie(Preferences);
cookie.Expires = DateTime.Now.AddDays(-1) ;
Response.Cookies.Add(cookie) ;
A Cookie Example
To try this example, begin by running the page, entering a name, and clicking the
Create Cookie button. Then, close the browser, and request the page again. The second
time, the page will find the cookie, read the name, and display a welcome message.
23
END OF LECTURE
24