1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft ASP Net 3.5 Step By Step (phần 12) ppt

30 277 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 30
Dung lượng 1,18 MB

Nội dung

Chapter 14 Session State 301 6. Now click Just Submit. What happens? Remember, Page_Load simply looks at the value of the _str member variable and stuffs it into the label. Pages (and HTTP handlers in general) are very short-lived objects. They live for the duration of the request and then are destroyed—along with all the data they hold. The _str member variable evaporated as soon as the last request fi nished. A new _str member variable (which was empty) was instantiated as soon as the page was re-created. To sum up, we saw in Chapter 4 that controls manage their own state. But in this case, we’re taking the data from the text box and storing them in a member variable in the Page class. The lifetime of the page is very short. The page lives long enough to gener- ate a response, and then it disappears. Any state you’ve stored as data members in the page disappears too. That’s why, when you click the Just Submit button, you don’t see the string displayed. You do see the string when Submit String is clicked because the member variable survives long enough to support the button’s Click event handler. 302 Part III Caching and State Management 7. Using session state is a way to solve this issue. To show this, add a new label to the page. This one will show the data as retrieved from the Session object: 8. Write code to store the string in session state. Have the SubmitString take the text from the TextBox1 and store it into the Session object. Then update the Page_Load method to display the value as it came from session state as shown below: public partial class _Default : System.Web.UI.Page { string _str = String.Empty; protected void Page_Load(object sender, EventArgs e) { this.LabelShowString.Text = this._str; this.LabelShowStringAsSessionState.Text = (String)this.Session["str"]; } Chapter 14 Session State 303 protected void SubmitString_Click(object sender, EventArgs e) { this._str = this.TextBox1.Text; this.Session["str"] = this.TextBox1.Text; this.LabelShowString.Text = this._str; this.LabelShowStringAsSessionState.Text = (String)this.Session["str"]; } } 9. Run the program. Type in a string and click the Submit String button. Both labels should contain data. The LabelShowString label will hold data because the SubmitString handler made the member variable assignment. The LabelShowStringAsSessionState label also shows data because the handler stored that text in session state. 304 Part III Caching and State Management 10. Now click the Just Submit button and see what happens: In this case, the page was simply submitted, causing only the Page_Load to be execut- ed. Page_Load displays both the _str member variable (which is empty because it lives and dies with the page) and the data from the Session object (which lives independently of the page). As you can see, session state is pretty convenient. However, we wouldn’t get very far if all we could do was store simple strings and scalars. Fortunately, the session dictionary stores all manner of CLR objects. Session State and More Complex Data ASP.NET’s Session object will store any (serializable) object running within the CLR. That goes for larger data—not just small strings or other scalar types. One of the most common uses for the Session object is for implementing features like shopping carts (or any other data that has to go with a particular client). For example, if you’re developing a commerce-oriented site for customers to purchase products, you’d probably implement a central database repre- senting your inventory. Then, as users sign on, they will have the opportunity to select items Chapter 14 Session State 305 from your inventory and place them in a temporary holding area associated with the session they’re running. In ASP.NET, that holding area is typically the Session object. A number of different collections are useful for managing shopping cart-like scenarios. Probably the easiest to use is the good ol’ ArrayList—an automatically sizing array that sup- ports both random access and the IList interface. However, for other scenarios you might use a DataTable, a DataSet, or some other more complex type. We took a quick look at ADO and data access in Chapter 11. The next example revisits data- bound controls (the DataList and the GridView). We’ll also work with the DataTable in depth. Session state, ADO.NET objects, and data-bound controls This example illustrates using ADO.NET objects, data-bound controls, and session state to transfer items from an inventory (represented as a DataList) to a collection of selected items (represented using a GridView). 1. Create a new page on the SessionState site named UseDataList.aspx. Add DataList to the page by copying the following code between the <div> tags on the generated page. The DataList will display the elements in the .NET References table from the Access database we saw in Chapter 11. <asp:DataList ID="DataList1" runat="server" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" Style="z-index: 100; left: 8px; position: absolute; top: 16px" OnItemCommand="DataList1_ItemCommand" Caption="Items in Inventory" > <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" /> <SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" /> <AlternatingItemStyle BackColor="#F7F7F7" /> <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" /> <ItemTemplate> ID: <asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>'></asp:Label><br /> Title: <asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>'></asp:Label><br /> AuthorLastName: <asp:Label ID="AuthorLastNameLabel" runat="server" Text='<%# Eval("AuthorLastName") %>'></asp:Label><br /> AuthorFirstName: <asp:Label ID="AuthorFirstNameLabel" runat="server" Text='<%# Eval("AuthorFirstName") %>'></asp:Label><br /> Topic: <asp:Label ID="TopicLabel" runat="server" 306 Part III Caching and State Management Text='<%# Eval("Topic") %>'></asp:Label><br /> Publisher: <asp:Label ID="PublisherLabel" runat="server" Text='<%# Eval("Publisher") %>'></asp:Label><br /> <br /> <asp:Button ID="SelectItem" runat="server" Text="Select Item" /> &nbsp; </ItemTemplate> <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" /> </asp:DataList> The Visual Studio designer should appear like this when done. 2. Stub out a shell for the SelectItem button on Click handler. Select DataList1 on the page. In the Properties dialog box within Visual Studio, click the lightning bolt button to get the events. In the edit box next to the ItemCommand event, type SelectItem. The button handler should be named DataList1_ItemCommand to match the identifi er Chapter 14 Session State 307 in the DataList1. We’ll use it shortly to move items from the inventory to the selected items table. public partial class UseDataList : System.Web.UI.Page { protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e) { } } 3. Go back to the code for the page and add some code to open a database and populate the DataList. Name the function GetInventory. The examples that come with this book include a database named ASPDotNetStepByStep.mdb that will work. Add the database from Chapter 11’s example to the App_Data folder of this project. You can use the con- nection string listed below to connect to the database. Make sure the database path points to the fi le correctly using your directory structure. public partial class UseDataList : System.Web.UI.Page { protected DataTable GetInventory() { string strConnection = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|ASPDotNetStepByStep.mdb"; DbProviderFactory f = DbProviderFactories.GetFactory("System.Data.OleDb"); DataTable dt = new DataTable(); using (DbConnection connection = f.CreateConnection()) { connection.ConnectionString = strConnection; connection.Open(); DbCommand command = f.CreateCommand(); command.CommandText = "Select * from DotNetReferences"; command.Connection = connection; IDataReader reader = command.ExecuteReader(); dt.Load(reader); reader.Close(); connection.Close(); } return dt; } protected DataTable BindToinventory() { 308 Part III Caching and State Management DataTable dt; dt = this.GetInventory(); this.DataList1.DataSource = dt; this.DataBind(); return dt; } // More goes here } 4. Now add a method named CreateSelectedItemsData. This will be a table into which se- lected items will be placed. The method will take a DataTable object that will describe the schema of the data in the live database (we’ll see how to get that soon). You can create an empty DataTable by constructing it and then adding Columns to the column collection. The schema coming from the database will have the column name and the data type. public partial class UseDataList : System.Web.UI.Page { protected DataTable CreateSelectedItemsTable(DataTable tableSchema) { DataTable tableSelectedItemsData = new DataTable(); foreach(DataColumn dc in tableSchema.Columns) { tableSelectedItemsData.Columns.Add(dc.ColumnName, dc.DataType); } return tableSelectedItemsData; } } 5. Add code to the Page_Load handler. When the initial request to a page is made (that is, if the request is not a postback), Page_Load should call BindToInventory (which re- turns the DataTable snapshot of the DotNetReferences table). Use the DataTable as the schema on which to base the selected items table. That is, declare an instance of a DataTable and assign it the result of CreateSelectedItemsTable. Then store the (now empty) table in the Session object using the key tableSelectedItems. public partial class UseDataList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { DataTable dt = BindToinventory(); DataTable tableSelectedItems = this.CreateSelectedItemsTable(dt); Session["tableSelectedItems"] = tableSelectedItems; } Chapter 14 Session State 309 } } Browse to the Web site to make sure that the database connects. It should look some- thing like this: 6. Now add a GridView to the page. Don’t bother to give it a data source. It represents the table of selected items held in session state. We’ll add that shortly. Make sure the AutoGenerateColumns property is set to true. 310 Part III Caching and State Management 7. Finally, add a handler for the SelectItem button. This method should move items from the inventory to the selected items table. You can get the selected item index from the DataListCommandEventArgs coming into the handler. Calling BindToInventory will set up the DataList data source so you can fetch the selected item. You may access the columns within the selected row using ordinal indices. From the values in each column, construct a new DataRow and add it to the selected items table. Store the modifi ed table back in session state. Finally, apply the new selected items table to the DataSource in the GridView1 and bind the GridView1. public partial class UseDataList : System.Web.UI.Page { protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e) { int nItemIndex = e.Item.ItemIndex; this.DataList1.SelectedIndex = nItemIndex; BindToinventory(); // Order of the columns is: // ID, Title, FirstName, LastName, Topic, Publisher DataTable dt = (DataTable)DataList1.DataSource; String strID = (dt.Rows[nItemIndex][0]).ToString(); String strTitle = (dt.Rows[nItemIndex][1]).ToString(); String strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString(); String strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString(); String strTopic = (dt.Rows[nItemIndex][4]).ToString(); String strPublisher = (dt.Rows[nItemIndex][5]).ToString(); DataTable tableSelectedItems; tableSelectedItems = (DataTable)Session["tableSelectedItems"]; DataRow dr = tableSelectedItems.NewRow(); dr[0] = strID; dr[1] = strTitle; dr[2] = strAuthorLastName; dr[3] = strAuthorFirstName; dr[4] = strTopic; dr[3] = strPublisher; tableSelectedItems.Rows.Add(dr); Session["tableSelectedItems"] = tableSelectedItems; this.GridView1.DataSource = tableSelectedItems; this.GridView1.DataBind(); } } 8. Run the site. When the page fi rst comes up, you should see only the inventory list on the left side of the page. Click the Select Item button on some of the items. You should see your browser post back to the server and render the DataList and the GridView with the newly added selected item. [...]... provided by ASP. NET to support session state, you may use your own database The allowCustomSqlDatabase setting turns this feature on When using SQL Server to store session data, ASP. NET has to act as a client of SQL Server Normally, the ASP. NET process identity is impersonated You may instruct ASP. NET to use the user credentials supplied to the identity configuration element within web.config by setting... Intro step, a Name and Address step, a Software step, a Hardware step, and a Submit information step That is, click the Add button to bring up the dialog box for entering steps “Name,” “Address,” “Software,” “Hardware,” and “Submit Information” are the Titles for these pages Make sure Intro uses StepType of Start 5 Make sure the Submit information step has its StepType set to Finish With all of the steps... attribute to Custom By setting the mode attribute to SQLServer, you tell ASP. NET to use a trusted connection The stateNetworkTimeout is for setting the number of seconds for the idle time limits of the TCP/IP network connection between the Web server and the state server, or between the SQL Server and the Web server The default is 10 Finally, you may instruct ASP. NET to use a custom provider by setting the... client ASP. NET offers three options for tracking the session ID—via cookies, the URL, or device profiles Tracking Session State with Cookies This is the default option for an ASP. NET Web site In this scenario, ASP. NET generates a hardto-guess identifier and uses it to store a new Session object You can see the session identifier come through the cookie collection if you have tracing turned on Notice how ASP. NET. .. in which you may configure ASP. NET session state Configuring Session State ASP. NET gives you several choices for managing session state You can turn it off completely, you may run session state in the ASP. NET worker process, you may run it on a separate state server, or you may run it from a SQL Server database Here’s a rundown of the options available: Don’t use it at all By disabling session state,... @"Provider =Microsoft. Jet.OLEDB.4.0; Data Source=|DataDirectory|ASPDotNetStepByStep.mdb"; DbProviderFactory f = DbProviderFactories.GetFactory("System.Data.OleDb"); DataTable dt = new DataTable(); using (DbConnection connection = f.CreateConnection()) { connection.ConnectionString = strConnection; connection.Open(); DbCommand command = f.CreateCommand(); command.CommandText = "Select * from DotNetReferences";... database Here’s the string provided by default: data source=localhost;Integrated Security=SSPI You may configure ASP. NET so it references a database on another machine Of course, you need to have SQL Server installed on the target machine to make this work In addition, you’ll find some SQL scripts to create the state databases in your NET system directory (C:\ WINDOWS \Microsoft. NET\ Framework\v2.0.50727 on this... together on a Web farm) Storing Session State in a State Server To have ASP. NET store session state on another server on your network, select StateServer from the SessionState mode control When you select this item, the dialog box will enable the Connection String text box and the network Timeout text box Insert the protocol, Internet Protocol (IP) address, and port for the state server in the Connection... controls to the steps First, select the Wizard in the designer and then choose Set Position from the Format menu Choose Absolute Now you can resize the Wizard Set the Height to 240px and the Width to 650px Now navigate to the step by selecting 320 Part III Caching and State Management the small arrow that appears on the upper right corner of the Wizard control Select the Intro step The Intro step gets a... click Check Out and the site redirects you to a checkout page From there, you are usually required to perform several distinct steps—setting up a payment method, confirming your order, and getting an order confirmation While you could code something like this in ASP. NET 1.x, ASP. NET includes a Wizard control to deal with this sort of multistage data collection If you were to develop a multistage input . DataTable GetInventory() { string strConnection = @"Provider =Microsoft. Jet.OLEDB.4.0; Data Source=|DataDirectory|ASPDotNetStepByStep.mdb"; DbProviderFactory f = DbProviderFactories.GetFactory("System.Data.OleDb"); . create the state databases in your .NET system directory (C: WINDOWS Microsoft. NET Frameworkv2.0 .50 727 on this machine at the time of this writing). The aspnet_regsql.exe tool will set up the. idle before ASP. NET abandons it and makes the session ID invalid. The maximum value is 52 5,601 minutes (one year), and the default is 20. Other Session Confi guration Settings ASP. NET supports

Ngày đăng: 07/07/2014, 06:20

TỪ KHÓA LIÊN QUAN