Maintaining State in a Web Application

Chia sẻ: Tuan Nghia | Ngày: | Loại File: PDF | Số trang:22

0
43
lượt xem
4
download

Maintaining State in a Web Application

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Maintaining 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

Chủ đề:
Lưu

Nội dung Text: Maintaining State in a Web Application

  1. Maintaining 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:
  2. int 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 void Page_Load(Object sender, EventArgs e) { int myInt;
  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 Response.AppendCookie(myHttpCookie); } else { // retrieve count and increment myInt by 1 myInt = Int32.Parse(Request.Cookies["count"].Value) + 1; } // set count value to myInt Response.Cookies["count"].Value = myInt.ToString(); // display myInt in myLabel myLabel.Text = "This page has been viewed "+ myInt.ToString() + " times."; } Note Notice that you can embed C# code directly into an .aspx file. The CookieTest.aspx file was created using Microsoft Notepad.
  4. To 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
  5. want 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 void Page_Load(Object sender, EventArgs e) { int myInt; // check if count is null if (ViewState["count"] == null) { // count is null, so initialize myInt to 1 myInt = 1; } else { // 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."; }
  6. Storing 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;
  7. You 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 void Page_Load(Object sender, EventArgs e) { int myInt; // check if count is null if (Session["count"] == null) { // count is null, so initialize myInt to 1 myInt = 1; } else { // retrieve count and increment myInt by 1 myInt = (int) Session["count"] + 1; }
  8. // set count value to myInt Session["count"] = myInt; // display myInt in myLabel myLabel.Text = "This page has been viewed "+ myInt.ToString() + " times."; } 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
  9. void Page_Load(Object sender, EventArgs e) { int myInt; // check if count is null if (Application["count"] == null) { // count is null, so initialize myInt to 1 myInt = 1; } else { // 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."; }
  10. 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.
  11. 2. 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.
  12. 6. 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) 5. { 6. // Put user code to initialize the page here 7. if (!this.IsPostBack) 8. { 9. sqlDataAdapter1.Fill(dataSet11, "Products"); 10. this.DataBind();
  13. 11. } 12. } The Fill() method retrieves the rows from the Products table and populates dataSet11 with those rows. The DataBind() method then fills the Products DataTable in dataSet11 with the rows retrieved from the Products table. This causes the rows to be displayed in the DataGrid of your form. To run your form, select Debug ➣ Start Without Debugging, or press Ctl+F5 on your keyboard (see Figure 15.8). Figure 15.8: The running form As you can see, a vertical scroll bar is displayed because of the number of rows retrieved from the Products table. In the next section, you'll learn how to customize your DataGrid. You'll see how you can control the number of rows displayed in your DataGrid so that no scroll bar appears, as well as control other aspects of your DataGrid. Customizing the DataGrid You customize your DataGrid by first selecting the DataGrid control and then clicking the Property Builder link at the bottom of the Properties window. This displays the Properties dialog box for your DataGrid. The Properties dialog box is divided into five areas: General, Columns, Paging, Format, and Borders. General Properties
  14. You use the General properties to set the data source for your DataGrid and whether you want a header and footer to displayed, among other properties. Set your General properties as shown in Figure 15.9. Figure 15.9: The General properties The General properties are as follows: • DataSource The DataSource is the source of the data for your DataGrid. In this example, the DataSource is dataSet11. • DataMember The DataMember is the name of the table to which your DataGrid is bound. In this example, the DataMember is Products. • Data Key Field The Data Key Field is the name of a column or expression that is associated with each row in your DataGrid but isn't actually shown. You typically use it to specify the primary key. • Header and Footer The header displays the name of the columns at the top of the DataGrid. Select Show Header and Show Footer. • Behavior You can sort columns in the header of your DataGrid. Select Allow Sorting so that your columns can be sorted. Columns Properties You use the Columns properties to select the columns to be displayed in your DataGrid and the header and footer text to be displayed for each column, among other properties. Click the Columns link of the Properties dialog box and set your Columns properties as shown in Figure 15.10.
  15. Figure 15.10: The Columns properties The Columns properties are as follows: • Create Columns Automatically At Run Time The Create Columns Automatically At Run Time check box specifies whether to automatically include all the columns for the DataSet in your DataGrid. When this check box is unselected, you can then set the other properties for each column individually. Unselect this check box. • Column List The Column List allows you to select columns from your DataSet for display in your DataGrid. You select columns from the Available Columns area on the left and add them to Selected Columns area on the right using the button containing the right arrow. Select (All Fields) from Available Columns, and add them to the Selected Columns. • BoundColumn Properties The BoundColumn properties allow you to set the properties for each column. You select the column you want to set in the Selected Columns area, and then you set the properties for that column. The fields you can set for each column are as follows: o Header Text The text you want to display in the header for a column. o Footer Text The text you want to display in the footer for a column. o Header Image The image you want to display in the header for a column. o Sort Expression The column or expression you want to use to sort the column by. Select UnitPrice as the Sort expression. o Data Field The name of column. o Data Formatting Expression Allows you to format a column value. You can use a formatting expression to format dates and numbers, among others. For example, {0:$##.00} formats a number, adds a dollar sign at the front, and displays two digits after the decimal point; thus, 19 is formatted
  16. as $19.00. Set the formatting expression for the UnitPrice column to {0:$##.00}. Paging Properties Next, click on the Paging link of the Properties dialog box. Normally, all the rows retrieved by a SELECT statement are displayed on a single page for the DataGrid. You can use the Paging properties to split all the rows into separate pages, with a fixed number of rows on each page in your DataGrid. You can then select the buttons to navigate between these pages of rows. You'll set your page size to five rows with Next and Previous buttons to navigate between the pages of rows. Set your Paging properties as shown in Figure 15.11. Figure 15.11: The Paging properties The Paging properties are as follows: • Allow Paging Controls whether paging is enabled. Check the Allow Paging box. • Page Size Controls the number of rows displayed on each page. Set your Page Size to 5. • Show Navigation Buttons The Show Navigation Buttons check box controls whether navigation buttons are displayed. These buttons allow you to navigate between pages of rows. Check the Show Navigation Buttons box. • Position Allows you to set the position of the navigation buttons. Set the Position to Bottom. • Mode Controls the type of navigation buttons displayed. You can use Next and Previous buttons or page numbers to navigate between pages. Set the Mode to Next, Previous Buttons.
  17. • Next Page Button Text Sets the text displayed on the Next page button. Leave this as > so that a greater-than character (>) is displayed. • Previous Page Button Text Sets the text displayed on the Previous page button. Leave this as < so that a less-than character (
  18. • Font Name The Font Name option specifies the font used to display the text. Set the Font Name to Arial. • Font Size The Font Size option controls the size of the font used to display the text. • Bold, Italic, Underline, Strikeout, Overline The Bold, Italic, Underline, Strikeout, and Overline options control the character formatting for the text. • Horizontal Alignment The Horizontal Alignment option specifies the position of the text in the cell. Borders Properties Next, click on the Borders link of the Properties dialog box. You use the Borders properties to control the padding, spacing, and appearance of the grid lines in your DataGrid. You'll set the border color of the grid lines in your DataGrid to blue. Set your Borders properties as shown in Figure 15.13. Figure 15.13: The Borders properties The Borders properties are as follows: • Cell Padding Controls the amount of space (in pixels) between the edge of a cell and the cell contents in your DataGrid. • Cell Spacing Controls the amount of space (in pixels) between each element in your DataGrid. • Grid Lines Specifies the direction of the grid lines in your DataGrid. • Border Color Specifies the color of the grid lines in your DataGrid. Set this to blue. • Border Width Controls the width and units of the grid lines in your DataGrid.
  19. Once you've set your properties, click the OK button to continue. Next, you'll code the PageIndexChanged() event handler to allow navigation of the rows in your DataGrid. Coding the PageIndexChanged() Event Handler As mentioned earlier, in addition to enabling paging in the Paging properties window, you'll also need to add some code to your DataGrid, specifically, to the PageIndexChanged() event handler method. This method is called whenever you change the page in the DataGrid on your running Web page. Before you add the required code, you first select your DataGrid, and then you click the Events button in the Properties window to display the events for your DataGrid, as shown in Figure 15.14. Figure 15.14: Displaying the DataGrid events Double-click the PageIndexChanged event and set your DataGrid1_PageIndexChanged() method as follows: private void DataGrid1_PageIndexChanged( object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) { DataGrid1.CurrentPageIndex = e.NewPageIndex;
  20. sqlDataAdapter1.Fill(dataSet11, "Products"); DataGrid1.DataBind(); } The first statement inside the method body is as follows: DataGrid1.CurrentPageIndex = e.NewPageIndex; This statement sets the current page displayed in DataGrid1 to the new page that is selected using the navigation buttons in the running form. You set the current page for DataGrid1 using the CurrentPageIndex property, and you get the new page from the NewPageIndex property of the DataGridPageChangedEventArgs object. By setting DataGrid1.CurrentPageIndex equal to e.NewPageIndex, the navigation to the new page of rows is performed. The second statement is as follows: sqlDataAdapter1.Fill(dataSet11, "Products"); This statement calls the Fill() method of sqlDataAdapter1 to populate dataSet11 with the next set of rows from the Products table. The third statement is as follows: DataGrid1.DataBind(); This statement calls the DataBind() method of DataGrid1, causing the new set of rows to be displayed. Note With VS .NET, you can also go to the code view and use the top drop-down menus to create the signature for events. This applies to any events that you add. Of course, double-clicking on events to get the "default" event is easier, but there are other events for each control. Run your form by pressing Ctrl+F5 on your keyboard. Figure 15.15 shows the running form.

CÓ THỂ BẠN MUỐN DOWNLOAD

Đồng bộ tài khoản