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

Beginning Microsoft Visual C# 2008 PHẦN 6 doc

135 288 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 135
Dung lượng 2,88 MB

Nội dung

Chapter 19: Basic Web Programming 639 The label labelResult again has a Text property where the result is set: labelResult.Text = String.Format(“{0} {1} selected the event {2}”, firstName, lastName, selectedEvent); Instead of displaying the results on the same page, ASP.NET makes it easy to display the results in a different page, as shown in the following Try It Out. Try It Out Displaying the Results in a Second Page 1. Create a new WebForm with the name ResultsPage.aspx . 2. Add a label to the ResultsPage with the name labelResult . 3. Add code to the Page_Load method to the class _ResultsPage as shown here: public partial class _ResultsPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { DropDownList dropDownListEvents = (DropDownList)PreviousPage.FindControl(“dropDownListEvents”); string selectedEvent = dropDownListEvents.SelectedValue; string firstName = ((TextBox)PreviousPage.FindControl(“textFirstName”)).Text; string lastName = ((TextBox)PreviousPage.FindControl(“textLastName”)).Text; string email = ((TextBox)PreviousPage.FindControl(“textEmail”)).Text; labelResult.Text = String.Format(“{0} {1} selected the event {2}”, firstName, lastName, selectedEvent); } catch { labelResult.Text = “The originating page must contain “ + “textFirstName, textLastName, textEmail controls”; } } } 4. Set the Default.aspx page ’ s Submit button ’ s PostbackUrl property to ResultsPage.aspx . c19.indd 639c19.indd 639 3/24/08 4:33:09 PM3/24/08 4:33:09 PM Part III: Web Programming 640 5. You can remove the Click event handler of the Submit button because it is not required anymore. 6. Start the Default.aspx page, fill in some data, and click the Submit button. You are redirected to the page ResultsPage.aspx , where the entered data is displayed. How It Works With ASP.NET, the Button control implements the property PostbackUrl to define the page that should be requested from the Web server. This property creates client - side JavaScript code to request the defined page with the client - side onclick handler of the Submit button: < input type=”submit” name=”buttonSubmit” value=”Submit” onclick=”javascript:webForm_DoPostBackWithOptions( new WebForm_PostBackOptions( & quot;buttonSubmit & quot;, & quot; & quot;, false, & quot; & quot;, & quot;ResultPage.aspx & quot;, false, false))” id=”buttonSubmit” / > The browser sends all the data from the form inside the first page to the new page. However, inside the newly requested page it is necessary to get the data from controls that have been defined with the previous page. To access the controls from a previous page, the Page class defines the property PreviousPage . PreviousPage returns a Page object, where the controls of this page can be accessed using the FindControl() method. FindControl() is defined to return a Control object, so you must cast the return value to the control type that is searched: DropDownList dropDownListEvents = (DropDownList)PreviousPage.FindControl(“dropDownListEvents”); Instead of using the FindControl() method to access the values of the previous page, access to the previous page can be strongly typed, which is less error prone during development. To make this possible, the next Try It Out defines a custom struct that is returned with a property from the default_aspx class. Try It Out Creating a Strongly Typed PreviousPage 1. Create the App_Code folder in the Web application by selecting the Web folder in the Solution Explorer and selecting Website Add Folder App_Code Folder. 2. In the Solution Explorer, select the App_Code folder and add a new C# file named RegistrationInformation.cs by selecting Website Add New Item Class. 3. Implement the struct RegistrationInformation in the file RegistrationInformation.cs as shown: public struct RegistrationInformation { public string FirstName { get; set; } public string LastName { get; set; } c19.indd 640c19.indd 640 3/24/08 4:33:09 PM3/24/08 4:33:09 PM Chapter 19: Basic Web Programming 641 public string Email { get; set; } public string SelectedEvent { get; set; } } 4. Add the public property RegistrationInformation to the class _Default in the file Default.aspx.cs : public RegistrationInformation RegistrationInformation { get { return new RegistrationInformation() { FirstName = textFirstName.Text, LastName = textLastName.Text, Email = textEmail.Text, SelectedEvent = dropDownListEvents.SelectedValue }; } } 5. Add the PreviousPageType directive to the file ResultPage.aspx following the Page directive: < %@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”ResultPage.aspx.cs” Inherits=”ResultPage_aspx” % > < %@ PreviousPageType VirtualPath=”~/Default.aspx” % > 6. Within the Page_Load() method of the class _ResultsPage , now the code can be simplified: protected void Page_Load(object sender, EventArgs e) { try { RegistrationInformation ri = PreviousPage.RegistrationInformation; labelResult.Text = String.Format(“{0} {1} selected the event {2}”, ri.FirstName, ri.LastName, ri.SelectedEvent); } catch { labelResult.Text = “The originating page must contain “ + “textFirstName, textLastName, textEmail controls”; } } c19.indd 641c19.indd 641 3/24/08 4:33:09 PM3/24/08 4:33:09 PM Part III: Web Programming 642 Input Validation When users enter data, it should be checked to confirm that the data is valid. The check can happen on the client and on the server. Checking the data on the client can be done by using JavaScript. However, if the data is checked on the client using JavaScript, it should also be checked on the server, because you can never fully trust the client. It is possible to disable JavaScript in the browser, and hackers can use different JavaScript functions that accept incorrect input. It is absolutely necessary to check the data on the server. Checking the data on the client as well leads to better performance, as no round - trips occur to the server until the data is validated on the client. With ASP.NET it is not necessary to write the validation functions yourself. Many validation controls exist that create both client - and server - side validation. The following example shows the RequiredFieldValidator validation control that is associated with the text box textFirstname . All validator controls have in common the properties ErrorMessage and ControlToValidate . If the input is not correct, then ErrorMessage defines the message that is displayed. By default, the error message is displayed where the validator control is positioned. The property ControlToValidate defines the control where the input is checked. < asp:TextBox ID=”textFirstname” runat=”server” > < /asp:TextBox > < asp:RequiredFieldValidator ID=”RequiredFieldValidator1” runat=”server” ErrorMessage=”Enter your first name” ControlToValidate=”textFirstName” > < /asp:RequiredFieldValidator > The following table lists and describes all the validation controls: Control Description RequiredFieldValidator Specifies that input is required with the control that is validated. If the control to validate has an initial value set, which the user has to change, you can set this initial value with the InitialValue property of the validator control. RangeValidator Defines a minimum and maximum value that the user is allowed to enter. The specific properties of the control are MinimumValue and MaximumValue . RegularExpressionValidator With the ValidationExpression property a regular expression using Perl 5 syntax can be set to check the user input. c19.indd 642c19.indd 642 3/24/08 4:33:10 PM3/24/08 4:33:10 PM Chapter 19: Basic Web Programming 643 Control Description CompareValidator Compares multiple values (such as passwords). Not only does this validator support comparing two values for equality, additional options can be set with the Operator property. The Operator property is of type ValidationCompareOperator , which defines enumeration values such as Equal , NotEqual , GreaterThan , and DataTypeCheck . Using DataTypeCheck , the input value can be checked to determine whether it is of a specific data type, e.g., correct date input. CustomValidator If the other validator controls don ’ t fulfill the requirements of the validation, the CustomValidator can be used. With the CustomValidator , both a client - and server - side validation function can be defined. ValidationSummary Writes a summary for a page instead of writing error messages directly to the input controls . With the sample application that you ’ ve created until now, the user can input first name, last name, and e - mail address. In the following Try It Out, you extend the application by using validation controls. Try It Out Checking for Required Input and E-mail Address 1. Open the previously created project EventRegistrationWeb using Visual Studio. 2. Open the file default.aspx . 3. Add a new column to the table by selecting the right column in the Design View of the editor and choosing Table Insert Column to the Right. 4. First name, last name, and e - mail address are required inputs. A check is done to determine whether the e - mail address has the correct syntax. Add three RequiredFieldValidator controls and one RegularExpressionValidator control, as shown in Figure 19 - 9 . Figure 19-9 c19.indd 643c19.indd 643 3/24/08 4:33:10 PM3/24/08 4:33:10 PM Part III: Web Programming 644 5. Configure the validation controls as defined in this table: Validation Control Property Value RequiredFieldValidator1 ErrorMessage First name is required. ControlToValidate textFirstName RequiredFieldValidator2 ErrorMessage Last name is required. ControlToValidate textLastName RequiredFieldValidator3 ErrorMessage Email is required. ControlToValidate textEmail Display Dynamic RegularExpressionValidator1 ErrorMessage Enter a valid email. ControlToValidate textEmail ValidationExpression \w+([ - +.’]\w+)*@\w+([ - .]\w+)*\.\w+([ - .]\w+)* Display Dynamic 6. It is not necessary to enter the regular expression manually. Instead, you can click the ellipsis button of the ValidationEpression property in the Properties window to start the Regular Expression Editor, shown in Figure 19 - 10 . This editor provides some predefined regular expressions, including the regular expression to check for an Internet e - mail address. Figure 19-10 c19.indd 644c19.indd 644 3/24/08 4:33:10 PM3/24/08 4:33:10 PM Chapter 19: Basic Web Programming 645 7. If a postback is done to a page that is different from the page that includes the validator controls (using the PostBackUrl property that was set earlier), in the new page you must verify that the result of the previous page was valid, using the IsValid property. Add this code to the Page_Load() method of the _ResultsPage class: protected void Page_Load(object sender, EventArgs e) { try { if (!PreviousPage.IsValid) { labelResult.Text = “Error in previous page”; return; } // 8. Now you can start the application. When data is not entered or not entered correctly, the validator controls show error messages, as shown in Figure 19 - 11 . Figure 19-11 How It Works The validator controls create both client - side JavaScript code to verify input on the client, and server - side code to validate input on the server. It is also possible to turn JavaScript off by setting the validator property EnableClientScript to false . Instead of changing the property with every validator control, you can also turn off JavaScript by setting the property ClientTarget of the Page class. Depending on the client type, the ASP.NET controls might return JavaScript to the client. This behavior depends on the ClientTarget property. By default, the ClientTarget is set to “ automatic ” , where, depending on the Web browser ’ s functionality, scripting code is returned or not. If the ClientTarget is set to “ downlevel ” , then scripting code is not returned for any clients, while setting the ClientTarget property to “ uplevel ” always returns scripting code. c19.indd 645c19.indd 645 3/24/08 4:33:11 PM3/24/08 4:33:11 PM Part III: Web Programming 646 Setting the property ClientTarget can be done inside the Page_Load() method of the Page class: protected void Page_Load(object sender, EventArgs e) { ClientTarget = “downlevel”; } State Management The HTTP protocol is stateless. The connection that is initiated from the client to the server can be closed after every request. However, normally it is necessary to remember some client information from one page to the other. There are several ways to accomplish this. The main difference among the various ways to keep state is whether the state is stored on the client or on the server. The following table shows an overview of state management techniques and how long the state can be valid: State Type Client or Server Resource Time Valid ViewState Client Within a single page only . Cookie Client Temporary cookies are deleted when the browser is closed; permanent cookies are stored on the disk of the client system. Session Server Session state is associated with a browser session. The session is invalidated with a timeout (by default, 20 minutes). Application Server Application state is shared among all clients. This state is valid until the server restarts. Cache Server Similar to application state, cache is shared. However, when the cache should be invalidated, there ’ s much better control. Now let ’ s take a more detailed look at these techniques. Client - Side State Management In this section, you are going to step into client - side state management by looking at two techniques: ViewState and cookies. c19.indd 646c19.indd 646 3/24/08 4:33:11 PM3/24/08 4:33:11 PM Chapter 19: Basic Web Programming 647 ViewState One technique to store state on the client was already discussed: ViewState. ViewState is used automatically by the Web server controls to make events work. The ViewState contains the same state as the control when sent to the client. When the browser sends the form back to the server, the ViewState contains the original values, but the values of the controls that are sent contain the new values. If there ’ s a difference, the corresponding event handlers are invoked. The disadvantage to using ViewState is that data is always transferred from the server to the client, and vice versa, which increases network traffic. To reduce network traffic, ViewState can be turned off. To do so for all controls within the page, set the EnableViewState property to false with the Page directive: < %@ Page Language=”C#” AutoEventWireUp=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” EnableViewState=”false” % > The ViewState can also be configured on a control by setting the EnableViewState property of a control. Regardless of what the page configuration says, when the EnableViewState property is defined for the control, the control value is used. The value of the page configuration is used only for these controls when the ViewState is not configured. It is also possible to store custom data inside the ViewState. This can be done by using an indexer with the ViewState property of the Page class. You can define a name that is used to access the ViewState value with the index argument: ViewState[“mydata”] = “my data”; You can read the previously stored ViewState as shown here: string mydata = (string)ViewState[“mydata”]; In the HTML code that is sent to the client, you can see the ViewState of the complete page within a hidden field: < input type=”hidden” name=”__VIEWSTATE” value=”/wEPDwUKLTU4NzY5NTcwNw8WAh4HbXlzdGF0ZQUFbXl2YWwWAgIDD2QWAg IFDw8WAh4EVGV4dAUFbXl2YWxkZGTCdCywUOcAW97aKpcjt1tzJ7ByUA==” / > Using hidden fields has the advantage that every browser can use this feature, and the user cannot turn it off. The ViewState is only remembered within a page. If the state should be valid across different pages, then using cookies is an option for state on the client. Cookies A cookie is defined in the HTTP header. Use the HttpResponse class to send a cookie to the client. Response is a property of the Page class that returns an object of type HttpResponse . The HttpResponse class defines the Cookies property that returns an HttpCookieCollection . Multiple cookies can be returned to the client with the HttpCookieCollection . c19.indd 647c19.indd 647 3/24/08 4:33:12 PM3/24/08 4:33:12 PM Part III: Web Programming 648 The following sample code shows how a cookie can be sent to the client. First, an HttpCookie object is instantiated. In the constructor of this class, the name of the cookie is set — here it is mycookie . The HttpCookie class has a Values property to add multiple cookie values. If you just have one cookie value to return, you can use the Value property instead. However, if you plan to send multiple cookie values, it is better to add the values to a single cookie instead of using multiple cookies. string myval = “myval”; HttpCookie cookie = new HttpCookie(“mycookie”); cookie.Values.Add(“mystate”, myval); Response.Cookies.Add(cookie); Cookies can be temporary and valid within a browser session, or they can be stored on the client disk. To make the cookie permanent, the Expires property must be set with the HttpCookie object. With the Expires property, a date defines when the cookie is not valid anymore; here, it is set to a date three months from the current date. Although a specific date can be set, there is no guarantee that the cookie is stored until the date is reached. The user can delete the cookie, and the browser application also deletes the cookie if too many cookies are stored locally. The browser has a limit of 20 cookies for a single server, and 300 cookies for all servers. When the limit is reached, the cookies that haven ’ t been used for some time are deleted. HttpCookie cookie = new HttpCookie(“mycookie”); cookie.Values.Add(“mystate”, “myval”); cookie.Expires = DateTime.Now.AddMonths(3); Response.Cookies.Add(cookie); When the client requests a page from the server, and a cookie for this server is available on the client, the cookie is sent to the server as part of the HTTP request. Reading the cookie in the ASP.NET page can be done by accessing the cookies collection in the HttpRequest object. Similarly to the HTTP response, the Page class has a Request property that returns an object of type HttpRequest . The property Cookies returns an HttpCookieCollection that can now be used to read the cookies sent by the client. A cookie can be accessed by its name with the indexer, and then the Values property of the HttpCookie is used to get the value from the cookie: HttpCookie cookie = Request.Cookies[“mycookie”]; string myval = cookie.Values[“mystate”]; ASP.NET makes it easy to use cookies, but you must be aware of the cookie ’ s restrictions. Recall that a browser accepts just 20 cookies from a single server and 300 cookies for all servers. There ’ s also a restriction regarding the size of a cookie, which cannot store more than 4K of data. These restrictions ensure that the client disk won ’ t be filled with cookies. Server - Side State Management Instead of remembering state with the client, it is also possible to remember state with the server. Using client - side state has the disadvantage that the data sent across the network increases. Using server - side state has the disadvantage that the server must allocate resources for its clients. Let ’ s look into the server - side state management techniques. c19.indd 648c19.indd 648 3/24/08 4:33:12 PM3/24/08 4:33:12 PM [...]... is, click OK The next dialog (shown in Figure 19-27) opens, for storing the connection string 66 3 c19.indd 66 3 3/24/08 4:33:19 PM Part III: Web Programming Figure 19- 26 8 Click the check box to save the connection and enter the connection string name EventsConnectionString Click Next Figure 19-27 66 4 c19.indd 66 4 3/24/08 4:33:19 PM Chapter 19: Basic Web Programming 9 In the next dialog, select the Events... 19-23 opens 4 Enter (local) for the server name, and BegVCSharpEvents for the database name Figure 19-23 66 0 c19.indd 66 0 3/24/08 4:33:18 PM Chapter 19: Basic Web Programming 5 After the database is created, select the new database in Server Explorer 6 Select the entry Tables below the database, and from Visual Studio select Data New Table 7 Enter the following column names and data types (see Figure 19-24)... grid control Within the element, all bound columns for displaying data are shown HeaderText defines the text of the header and DataField defines the field name within the data source 66 6 c19.indd 66 6 3/24/08 4:33:20 PM Chapter 19: Basic Web Programming The data source is defined with the element, where the SelectCommand defines how the data is read from the database, and... here 65 6 c19.indd 65 6 3/24/08 4:33: 16 PM Chapter 19: Basic Web Programming Within the Intro subfolder, you can see another configuration file, web.config The authentication section is missing from this configuration file... SqlDataSource with the name EventsDatasource, as shown in Figure 19-29 Figure 19-29 66 5 c19.indd 66 5 3/24/08 4:33:20 PM Part III: Web Programming 12 For a more beautiful layout of the GridView control, select AutoFormat from the smart tag and select the scheme Lilacs in Mist, as shown in Figure 19-30 Figure 19-30 13 Start the page with Visual Studio, where you will see the events in a nice table like the one... shown in Figure 19-13 ASP.NET 65 2 c19.indd 65 2 3/24/08 4:33:14 PM Chapter 19: Basic Web Programming Figure 19-13 5 Click the link to the Security Setup Wizard In the Welcome Screen, click the Next button From step 2 of the wizard, select the access method From the Internet, as shown in Figure 19-14 Figure 19-14 65 3 c19.indd 65 3 3/24/08 4:33:14 PM Part III: Web Programming 6 Click Next Here, step 3, you... 19- 16 8 After one user is successfully created, click the Next button for step 6 of the wizard (see Figure 19-17) Here, you can configure which users are allowed or denied access to the Web site or specific directories Add a rule to deny anonymous users Next, select the Intro directory and add a rule to allow anonymous users Then click the Next button and finally the Finish button 65 4 c19.indd 65 4... data view and data source A data source control is associated with a data source such as an XML file, a SQL database, or a NET class; data views are connected with a data source to represent data 66 1 c19.indd 66 1 3/24/08 4:33:18 PM Part III: Web Programming The following table describes all the data controls: Data Control Description GridView Displays data with rows and columns DataList Displays a single... creating links and references with a Web site This feature is discussed in Chapter 20 In the next Try It Out, you use a GridView control to display and edit data from the previously created database 66 2 c19.indd 66 2 3/24/08 4:33:18 PM Chapter 19: Basic Web Programming Try It Out Using a GridView Control to Display Data 1 In the Solution Explorer, create a new regular folder Admin 2 Create a new Web page... /> Now the GridView control should be configured differently In the next Try It Out, the ID is no longer displayed to the user, and the date-time display shows only the date 66 7 c19.indd 66 7 3/24/08 4:33:20 PM Part III: Web Programming Try It Out 1 Configuring the GridView Control Select the smart tag of the GridView control and select the Edit Columns menu The Fields dialog, shown . /system.web > < /configuration > c19.indd 65 6c19.indd 65 6 3/24/08 4:33: 16 PM3/24/08 4:33: 16 PM Chapter 19: Basic Web Programming 65 7 Within the Intro subfolder, you can see another. Finish button. c19.indd 65 4c19.indd 65 4 3/24/08 4:33:14 PM3/24/08 4:33:14 PM Chapter 19: Basic Web Programming 65 5 Figure 19-17 Figure 19- 16 c19.indd 65 5c19.indd 65 5 3/24/08 4:33:15 PM3/24/08. at two techniques: ViewState and cookies. c19.indd 64 6c19.indd 64 6 3/24/08 4:33:11 PM3/24/08 4:33:11 PM Chapter 19: Basic Web Programming 64 7 ViewState One technique to store state on the

Ngày đăng: 09/08/2014, 14:21

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN