Storing Information on the Client To store information on the client, you can use cookies or the Page object's ViewState property.. // check if count is null if Request.Cookies["count"
Trang 1Maintaining State in a Web Application
The Hypertext Transport Protocol (HTTP) doesn't maintain state between pages served by your Web server during each round-trip This means that any
information you provided in a form is for-gotten when you get a new page If you're simply receiving static HTML Web pages, then this isn't a problem If you're placing an order for a product, however, then the server needs to
remember what you ordered
To get the Web server to remember what you did during the last round-trip, you can store information on the server or on the client computer the browser is running on
Storing information on the client means you don't use up any resources on the server to store that information, and your Web application can potentially
handle many more users Storing information on the server gives you more control of the stored information, but since this consumes server resources, you need to be careful not to store too much; otherwise your Web application won't
be able to handle many users
Storing Information on the Client
To store information on the client, you can use cookies or the Page object's ViewState property Let's take a look at how you use cookies and the ViewState property
Storing Information using Cookies
A cookie is a name and value pair that is stored in a small file that resides on the
hard drive of the client computer You use the name to identify the value being stored; both the name and value are string objects
Warning Cookies are potentially problematic because the user can configure
their browser to prevent cookies from being stored Also, a browser stores only a limited number of cookies: 300 in total and no more than
20 per Web server You should therefore use cookies sparingly-if at all
The following example creates an int variable named myInt that is set to 1 and creates an HttpCookie object that stores myInt under the name count:
Trang 2int myInt = 1;
HttpCookie myHttpCookie = new HttpCookie("count", myInt.ToString()); Because a cookie stores the value as a string, you use the ToString() method to convert myInt to a string before storing it in myHttpCookie
To store the cookie on the client, you call the AppendCookie() method of the Page object's Response:
Response.AppendCookie(myHttpCookie);
The Response object is the HTTP response sent by the Web server to the
browser When this code is run, it causes the browser to store the cookie on the client computer's hard disk in the directory specified in the settings for the browser
You can retrieve the count value from the Cookies collection of the Request object:
myInt = Int32.Parse(Request.Cookies["count"].Value);
The Request object is sent by the browser to the Web server and contains the cookie previously set Because the count value is stored as a string, you use the static Parse() method of the Int32 structure to convert the string to an int
Listing 15.6 shows an example ASP.NET application that uses a cookie to keep track of the number of times the page has been viewed
Listing 15.6: CookieTest.aspx
<!
CookieTest.aspx illustrates the use of a cookie to
store information on the client
>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
{
int myInt;
Trang 3// check if count is null
if (Request.Cookies["count"] == null)
{
// count is null, so initialize myInt to 1
myInt = 1;
// create an HttpCookie object
HttpCookie myHttpCookie = new HttpCookie("count", myInt.ToString());
// add HttpCookie object to Response
// display myInt in myLabel
myLabel.Text = "This page has been viewed "+ myInt.ToString() +
Note Notice that you can embed C# code directly into an aspx file The
CookieTest.aspx file was created using Microsoft Notepad
Trang 4To run CookieText.aspx, simply copy this file into your Inetpub\wwwroot directory and point your browser to http://localhost/CookieTest.aspx Figure 15.23 shows the page generated by CookieTest.aspx-assuming that the button
on the page has been repeatedly pressed
Figure 15.23: The running CookieTest.aspx page
Storing Information using the ViewState Property
You use the Page object's ViewState property to access a StateBag object, which stores a collection of name and value pairs on the client computer You use the name to identify the value being stored The name is a string and the value is an object Unlike a cookie, a user cannot prevent values from being stored using the ViewState property One use for the ViewState property would
be to store a user's name
Tip Since the values are sent back and forth between the client and the server,
you should store only a small amount of information using the ViewState
property This is still a better solution than using cookies because the user can always prevent cookies from being stored
The following example stores myInt under the name count:
int myInt = 1;
ViewState["count"] = myInt;
You can then retrieve the count value using the following code:
myInt = (int) ViewState["count"];
Because a value is stored as an object, you must cast it to the specific type you
Trang 5want to use In this example, the count value is cast to an int
Listing 15.7 shows an example ASP.NET page that uses the ViewState property
to keep track of the number of times the page has been viewed
Listing 15.7: ViewStateTest.aspx
<!
ViewStateTest.aspx illustrates the use of ViewState to
store information on the client
>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
// retrieve count and increment myInt by 1
myInt = (int) ViewState["count"] + 1;
}
// set count value to myInt
ViewState["count"] = myInt;
// display myInt in myLabel
myLabel.Text = "This page has been viewed "+ myInt.ToString() +
" times.";
}
</script>
</head>
Trang 6Storing Information on the Server
To store information on the server, you can use the Page object's Session,
Application, or Cache object These objects all store information in the form of name and value pairs, where the name is a string and the value is an object You can also store information in the database itself, which is the best solution if you need to store a lot of information about a user or the application Finally, you can of course always store information in static variables or objects
You'll learn about the Session, Application, and Cache objects in the next
sections I'll also discuss storing information about a Web application in the database
Storing Information Using a Session Object
A Session object allows you to store separate information for each user The information stored in the Session object remains on the server up to a default time of 20 minutes, after which the information is thrown away One use for the Session object might be to store the user's name
Tip Because each Session object stores information for a single user, store the
absolute minimum information for each user Otherwise, your Web server
could be swamped with Session objects and run out of memory, and your
application wouldn't support large numbers of users
The information is stored in name and value pairs, where the name is a string and the value is an object The following example stores myInt under the name count:
int myInt = 1;
Session["count"] = myInt;
Trang 7You can then retrieve the count value using the following code:
myInt = (int) Session["count"];
Because a value is stored as an object, you must cast it to the specific type you want to use In this example, the count value is cast to an int
Listing 15.8 shows an example ASP.NET page that uses the Session object to keep track of the number of times the page has been viewed This information
is specific to each user, and therefore shows the total number of times the page has been viewed by the current user
Listing 15.8: SessionObjectTest.aspx
<!
SessionObjectTest.aspx illustrates the use of the
Session object to store information on the server
This information is specific for each user
>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
// retrieve count and increment myInt by 1
myInt = (int) Session["count"] + 1;
}
Trang 8// set count value to myInt
Session["count"] = myInt;
// display myInt in myLabel
myLabel.Text = "This page has been viewed "+ myInt.ToString() +
Storing Information using the Application Object
The Application object allows you to store information that is shared for all users One use for the Application object might be to store a DataSet object containing a product catalog The information is stored in name and value pairs, where the name is a string and the value is an object
The following example stores myInt under the name count:
int myInt = 1;
Application["count"] = myInt;
You can then retrieve the count value using the following code:
myInt = (int) Application["count"];
Listing 15.9 shows an example ASP.NET page that uses the Application object
to keep track of the number of times the page has been viewed This
information is shared by all users, and therefore shows the total number of times the page has been viewed by all users
Listing 15.9: ApplicationObjectTest.aspx
Trang 9<!
ApplicationObjectTest.aspx illustrates the use of the
Application object to store information on the server
This information is shared for all users
>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
// retrieve count and increment myInt by 1
myInt = (int) Application["count"] + 1;
}
// set count value to myInt
Application["count"] = myInt;
// display myInt in myLabel
myLabel.Text = "This page has been viewed "+ myInt.ToString() + " times.";
Trang 10</form>
</body>
</html>
Storing Information using the Cache Object
Like the Application object, the Cache object is also shared for all users, but it
provides more functionality than the Application object For example, you can
control when the stored information is removed For more information about
the Cache object, consult the NET online documentation as described in
Chapter 1, "Introduction to Database Programming with ADO.NET." Look up
"Cache class" in the index of the online documentation
Storing Information using the Database
If you have a large amount of information to store about a user, store it in the
database rather than the Session object For example, if you're building a Web
site that a user can order products from, store their shopping cart in the
database
Using a DataGrid Control to Access a Database
A DataGrid allows you to access rows in a database table In the following sections, you'll learn how to create an ASP.NET Web application that uses a DataGrid control to access the rows in a database table The DataGrid you'll create will display the rows from the Products table of the Northwind database
Creating the Web Application
Perform the following steps:
1 To create the new project, select File ➣ New Project in VS NET Select Visual C# Projects from the Project Types area on the left of the New Project dialog box, and select ASP.NET Web Application from the Templates area on the right Enter
http://localhost/DataGrid-WebApplication in the Location field Click OK to
continue Your new project will contain a blank form
Trang 112 Next, you'll add a DataGrid control to your form To do this, select the DataGrid from the Toolbox and drag it to your form Figure 15.7 shows the form with the DataGrid
Figure 15.7: Form with a DataGrid
3 Next, you'll add a SqlConnection object and a SqlDataAdapter object to your form To add these objects, select the Products table in Server Explorer and drag it
to your form (Adding a SqlConnection object to a form was discussed in Chapter
6, "Introducing Windows Applications and ADO.NET," and in Chapter 7,
"Connecting to a Database.")
Note To display Server Explorer, select View ➣ Server Explorer, or press
Ctrl+Alt+S on your keyboard
4 After you drag the Products table to your form, VS NET creates a SqlConnection object named sqlConnection1 and a SqlDataAdapter object named
sqlDataAdapter1 Click your sqlConnection1 object to display the properties for this object in the Properties window To enable sqlConnection1 to access the database, you need to set the password for the connection To do this, you need to add a substring containing pwd to the ConnectionString property of
sqlConnection1 Add pwd=sa; to the ConnectionString property
Note If you don't have the password for the sa user, you'll need to get it from your
database administrator
5 Next, you'll modify the SQL SELECT statement used to retrieve the rows from the Products table Click the sqlDataAdapter1 object to display the properties for this object Click the addition icon to the left of the SelectCommand property to
display the dynamic properties One of the dynamic properties is the
CommandText property, which contains the SELECT statement
Trang 126 Click CommandText and then click the ellipsis button to display the Query
Builder You use Query Builder to define SQL statements You can type in the
SQL statement, or you can build it visually Uncheck all the columns except the
following: ProductID, ProductName, QuantityPerUnit, and UnitPrice This results
in the SQL SELECT statement being set to the following:
7 SELECT ProductID, ProductName, QuantityPerUnit, UnitPrice
8 FROM Products
9 Click the OK button to save your SELECT statement and close Query Builder Next, you need to create a DataSet object You use a DataSet object to store a local copy
of the information stored in the database A DataSet object can represent database
structures such as tables, rows, and columns In the example in this section, you'll use a DataSet object to store the rows from the Products table
1 Click an area of your form outside the DataGrid Next, click the Generate Dataset link near the bottom of the Properties window This displays the Generate Dataset dialog box Select the New radio button and make sure the text field to the right of this radio button contains DataSet1 Also, make sure the Add This Dataset To The Designer checkbox is checked Click the OK button to continue This adds a new DataSet object named dataSet11 to your form
2 Next, you'll need to set the DataSource property of your DataGrid to your DataSet object This sets the source of the data for your DataGrid and allows the rows from your DataSet to be displayed in your DataGrid To set the DataSource property, click your DataGrid object and set the DataSource property to dataSet11 Also, set the DataMember property to Products; this is the table with rows that are to be displayed by your DataGrid
3 Next, you'll need to add code to populate sqlDataAdapter1 with the rows retrieved
by your SELECT statement Typically, the best place to place this code is in the Page_Load() method of your form The Page_Load() method is called when the Web page containing your form is initially loaded or refreshed The IsPostBack property of a page is false the first time the page is loaded and true when the submit button of a form is pressed For performance, you'll generally want to retrieve rows only when the IsPostBack property is false; otherwise you might needlessly reload the rows from the database To view the code for your form, open the code for your form by selecting View ➣ Code or by pressing F7 on your keyboard Set your Page_Load() method to the following:
4 private void Page_Load(object sender, System.EventArgs e)