Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2009 Pearson Education, Inc. All rights reserved.

Similar presentations


Presentation on theme: " 2009 Pearson Education, Inc. All rights reserved."— Presentation transcript:

1  2009 Pearson Education, Inc. All rights reserved.
Chapter 23 Web App Development with ASP.NET  2009 Pearson Education, Inc. All rights reserved. © by Pearson Education, Inc. All Rights Reserved.

2 A fair question should be followed by a deed in silence.
Dante Alighieri You’ll come here and get books that will open your eyes, and your ears, and your curiosity, and turn you inside out or outside in. Ralph Waldo Emerson Rule One: Our client is always right Rule Two: If you think our client is wrong, see Rule One. Anonymous

3 Chapter 23 – ASP .Net, Web Forms and Web Controls
Moreover, you will learn: To create Web Forms. To create ASP.NET applications consisting of multiple Web Forms. To maintain state information about a user with session tracking and cookies. To use the Web Site Administration Tool to modify web application configuration settings.

4 OUTLINE © by Pearson Education, Inc. All Rights Reserved.

5 Web-Based Application Development
23.1 Introduction Web-Based Application Development Creates Web content for Web browser clients, includes HyperText Markup Language (HTML) Client-side scripting Images and binary data Web Forms (Web Form pages) File extension .aspx (Web Form pages) contain the Web page’s GUI Every ASPX files has a corresponding class written in a .NET compliant languages, such as C#. This class (the code-behind ASPX file .aspx.cs ) contain (functionality) written code, event handlers, utility (helper) methods and other supporting code

6 Web Forms has two components

7 23.2 Simple HTTP Transaction
WEB pages are HTML documents, are available via URL indicates the resource is to obtained using HTTP – host name is translated into an IP address /books – path or location of an actual (or virtual) directory on the WEB server’s file system; the virtual directory is translated into a real location on the server downloads.htm – the name of the resource HyperText Transfer Protocol (HTTP) Defines methods and headers which allows clients and servers exchange information in uniform way Domain Name Server (DNS) A computer that maintains a database of hostnames and their corresponding IP addresses, maintains a DNS lookup table which translates the hostname into an IP address Uniform Resource Locator (URL) is an IP address indicating the location of a resource All HTML documents have a corresponding URL Internet Information System (IIS) is the Web Server that programmers use when developing ASP applications

8 23.2 A Simple HTTP Transaction
Fig Client interacting with Web server. Step 1: Client sends the GET request – an HTTP method: GET /books/downloads.htm HTTP/ // version 1.1 When the server receives it searches through its system for the resource A GET request retrieves information from a server. A GET request can specify parameters in the URL e.g. A ? separates the query string from the rest of the URL in a request. A name/value pair is passed to the server with the name and the value separated by an equals sign (=). If multiple name/value pairs are submitted, pairs are separated by an ampersand (&). The server then sends a response to the client.

9 23.2 or step 1: POST request Software Engineering Observation 23.1
A POST request sends data to a server. A POST request sends form data as part of the HTTP message, not as part of the URL. Unlike GET, POST requests are not typically limited in length (2083 chrs in IE) The POST method is also sometimes preferred because it hides the data from the user. An HTTP request often posts data to a server-side form handler that processes the data. Software Engineering Observation 23.1 The data sent in a POST request is not part of the URL, and the user can’t see the data by default. However, there are tools available that expose this data, so you should not assume that the data is secure just because a POST request is used.

10 23.2 Simple HTTP Transactions (Cont.)
Browsers often cache (save on disk) web pages for quick reloading. An HTTP response can indicate the length of time for which the content remains “fresh.” This allows the browser to minimize the amount of data that must be downloaded to view a web page. Sometimes results of the search are catched

11 23.2 A Simple HTTP Transaction
Fig Client interacting with Web server. Step 2: The HTTP response method: HTTP/ OK // = success and then the server is // sending an HTML doc or HTTP/ Not found // = failure

12 23.2 A Simple HTTP Transaction
If success the server is sending an HTML doc in the form: 1. HTTP header This specifies the Multipurpose Internet Mail Extensions (MIME) type of the content Content-type: text/html or Content-type: text/plain or Content-type: image/gif 2. A blank line 3. The contents of the requested HTML doc

13 23.3 Multitier Applications Architecture
Web-based applications (n-tier applications) Tiers are logical groupings of functionality 1. Information Tier (data tier or bottom tier) Maintains data pertaining to the applications Usually stores data in a relational database management systems (RDBMS)

14 23.3 Multitier Applications Architecture
Fig Three-tier architecture. 2. Middle Tier (logic tier) business logic (rules) and logic to control interaction between the application's clients and data tier business rules dictates: how clients can access data and how application process data acts as an intermediary between data in the information tier and the application's clients, retrieved the data 3. Client Tier (presentation tier) the application user interface, typically a browser users interact directly with appl. through the user interface

15 client, server, application & database tiers
Multiple tiers including client, server, application & database Browsers have evolved from using basic HTTP to Downloading Active content Running scripting Downloading and installing Plug-ins

16 23.4 Your First Web Application
Visual Component Clickable buttons and other GUI components which users interact Nonvisual Component Hidden inputs that store any data that document author specifies such as address

17 Fig. | ASPX file that displays the web server’s time. (Part 2 of 2. )
Outline Visual Web Developer generates the markup shown here when you create the GUI. WebTime.aspx ( 1 of 2 ) ASP.NET comments begin with <%-- and terminate with --%>, and can span multiple lines. The Page directive specifies information needed by ASP.NET to process this file. The document type declaration, HTML documents have the root element html and markup information about the document in the head element. The form that contains our HTML text and controls is set to execute on the server, which generates equivalent HTML. The body contains the main content that the browser displays. Fig. | ASPX file that displays the web server’s time. (Part 2 of 2. )

18 Fig. | ASPX file that displays the web server’s time. (Part 2 of 2. )
Outline Markup for a label web control. WebTime.aspx ( 2 of 2 ) The asp: tag prefix indicates that the label is an ASP.NET web control, not an HTML element. In an ASPX file a directive is delimited by and %>. Fig. | ASPX file that displays the web server’s time. (Part 2 of 2. )

19 23.4 Your First Web Application (Cont.)
1. Examining an ASPX File The Page directive’s Language attribute specifies the code-behind file’s language. The CodeFile attribute specifies the code-behind filename. When AutoEventWireup is true, ASP.NET automatically treats a method of name Page_eventName (e.g. Page_Init, Page_Load) as an event handler. When AutoEvent­Wireup is set to false, you specify event handlers using attributes in the Page directive just as you would any other web control. The Inherits attribute (line 4) specifies the class (e.g. WebTime) in the code-behind file from which this ASP.NET class inherits.

20 23.4 Your First Web Application (Cont.)
HTML documents have the root element html and markup information about the document in the head element. Setting the runat attribute to "server" indicates that ASP.NET processes the element and its nested elements and generates the corresponding HTML. The body contains the main content that the browser displays. The form that contains our HTML text and controls is set to execute on the server, which generates equivalent HTML.

21 23.4 Your First Web Application (Cont.)
The ID attribute assigns a name to a control, used as an identifier (reference) the code-behind file. The asp: tag prefix indicates that the label is an ASP.NET web control, not an HTML element. Each web control maps to a corresponding HTML element or group of elements. Portability Tip 23.1 The same web control can map to different HTML elements, depending on the client browser and the web control’s property settings.

22 23.4 Your First Web Application (Cont.)
The asp:Label control maps to the HTML span element with the property values that were applied to our label A span element contains text with formatting styles. This control is processed on the server so that the server can translate the control into HTML. If this is not supported, the asp:Label element is written as text to the client.

23 Figure 23.5 presents the code-behind file.
Outline Figure 23.5 presents the code-behind file. WebTime.aspx.cs (1 of 2 ) The Page_Init method handles the page’s Init event, which indicates that the page is ready to be initialized. Retrieve the current time and formats it as hh:mm:ss. Fig | Code-behind file for a page that displays the web server’s time. (Part 1 of 2.) The Page_Init method handles the page’s Init event, which indicates that the page is ready to be initialized.

24 2. Relationship Between an ASPX File and a Code Behind File
The code-behind file inherits from class Page, which defines the general functionality of a web page. public partial class WebTime : System.Web.UI.Page The code-behind file contains a partial class. ASP.NET generates another partial class that defines the remainder of that class, based on the markup in the ASPX file. The first time the web page is requested, this class is compiled, and an instance is created. This instance represents our page - it creates the HTML that is sent to the client. Once an instance of the web page has been created, multiple clients can use it to access the page - no recompilation is necessary.

25 3. How the Code in an ASP.NET Web Page Executes
When an instance of the page is created, the PreInit event occurs first, invoking method Page_PreInit, which can be used to set a page’s theme. The Init event occurs next, invoking method Page_Init, which is used to initialize objects and other aspects of the page. Next, the Load event occurs, and the Page_Load event handler executes. The Init event is raised only once (when the page is first requested). The Load event is raised with every request. The page then processes any events that are generated by the page’s controls.

26 23.4 Your First Web Application (Cont.)
When the WebForm is ready for garbage collection (once a response has been generated and sent), an Unload event occurs, which calls Page_Unload, which typically releases resources used by the page.

27 Figure 23. 6 shows the HTML generated by ASP
Figure 23.6 shows the HTML generated by ASP.NET when a web browser requests WebTime.aspx (Fig. 23.4). Attribute method of the form element specifies the request method (usually get or post). The action attribute identifies the resource that will be requested when a form is submitted. Nonvisual form components, called hidden inputs, store data, such as addresses that the user doesn’t need to see. Fig | HTML/XHTML response when the browser requests WebTime.aspx. (Part 1 of 2. ) WebTime.html ( 1 of 2 ) Note: Literal HTML/XHTML elements are not changed

28 WebTime.html ( 2 of 2 ) The form contains a span element to represent the text in the label. Formatting properties of timeLabel are converted into the style attribute of the span element. Fig | HTML/XHTML response when the browser requests WebTime.aspx. (Part 2 of 2. )

29 23.4 Your First Web Application (Cont.)
To view this HTML, select View Source from the Page menu ( ) in Internet Explorer (or View > Page Source if you are using Firefox). Nonvisual form components, called hidden inputs, store data that the user doesn’t need to see. Attribute method of the form element specifies the request method (usually get or post). The action attribute identifies the resource that will be requested when a form is submitted.

30 23.4 Your First Web Application (Cont.)
When the form is processed on the server, the runat attribute is removed. Only those elements marked in the ASPX file with runat="server" are modified or replaced in the generated HTML.

31 23.4 Your First Web Application (Cont.)
23.4.1 Building an ASP.NET Web Application To build the WebTime application, perform the following steps in Visual Web Developer: Step 1: Creating the Web Application Project Select File > New Web Site... and choose ASP.NET Web Site in the Templates pane. Select File System from the drop-down list closest to Location. Set the Language drop-down list to Visual C#, and click OK.

32 23.4 Your First Web Application (Cont.)
Fig | Creating an ASP.NET Web Site in Visual Web Developer.

33 23.4 Your First Web Application (Cont.)
Step 2: Examining the Solution Explorer of the Newly Created Project The Solution Explorer is shown in Fig. 23.8. Nest Related Files View Code View Designer Copy Web Site Refresh Properties ASP.NET Configuration Data files folder ASPX file Code-behind file Website configuration file Fig | Solution Explorer window for project WebTime.

34 23.4 Your First Web Application (Cont.)
An ASPX file (i.e., Web Form) named Default.aspx is created for each new project. Visual Web Developer creates a code-behind file named Default.aspx.cs. The View Designer button opens the Web Form in Design mode. The Copy Web Site button allows you to copy the project’s files to another location, such as a remote web server. Finally, the ASP.NET Configuration button takes you to the Web Site Administration Tool.

35 23.4 Your First Web Application (Cont.)
Step 3: Examining the Toolbox in Visual Web Developer Figure 23.9 shows the Toolbox displayed in the IDE when the project loads.

36 23.4 Your First Web Application (Cont.)
Figure 23.9(a) displays the beginning of the Standard list of web controls. Figure 23.9(b) displays the remaining web controls, as well as the list of Data controls used in ASP.NET. Fig | Toolbox in Visual Web Developer.

37 23.4 Your First Web Application (Cont.)
Step 4: Examining the Web Forms Designer Figure 23.10 shows the Web Forms Designer in Source mode, which appears in the center of the IDE. Source mode button Source mode button Split mode button Design mode button Fig | Source mode of the Web Forms Designer.

38 23.4 Your First Web Application (Cont.)
When the project loads for the first time, the Web Forms Designer displays the autogenerated ASPX file in Source mode.

39 23.4 Your First Web Application (Cont.)
Clicking the Design button in the lower-left corner of the Web Forms Designer switches to Design mode (Fig. 23.11). Cursor Cursor’s current location Fig | Design mode of the Web Forms Designer. Design mode indicates the HTML/XHTML element path where the cursor is currently located.

40 23.4 Your First Web Application (Cont.)
You can also view both the markup and the web-page design at the same time by using Split mode, as shown in Fig. 23.12. Fig | Split mode of Web Forms Designer.

41 23.4 Your First Web Application (Cont.)
Step 5: Examining the Code-Behind File in the IDE The next figure (Fig. 23.13) displays the code-behind file generated by Visual Web Developer for Default.aspx. Fig | Code-behind file for Default.aspx generated by Visual Web Developer Right click the ASPX file in the Solution Explorer and select View Code to open the code-behind file.

42 23.4 Your First Web Application (Cont.)
Design: Step 6: Renaming the ASPX File Right click the ASPX file in the Solution Explorer and select Rename. Enter the new file name WebTime.aspx and press Enter. Both the ASPX file and the code-behind file are updated.

43 23.4 Your First Web Application (Cont.)
Step 7: Renaming the Class in the Code-Behind File and Updating the ASPX File Visual Studio’s refactoring tool, which automatically updates the existing references to this class in the rest of the project to reflect this change. Right click the class name in the partial class’s declaration and select Refactor > Rename… to open the Rename dialog (Fig. 23.14).

44 23.4 Your First Web Application (Cont.)
Fig | Rename dialog. Specify WebTime as the new class name and click OK.

45 23.4 Your First Web Application (Cont.)
Step 8: Changing the Title of the Page We change the page’s title from the default Untitled Page to A Simple Web Form Example. Open the ASPX file in Source mode and modify the text between the <title> tags. Alternatively, you can modify the Web Form’s Title property in the Properties window. To view the Web Form’s properties, select DOCUMENT from the drop-down list in the Properties window.

46 23.4 Your First Web Application (Cont.)
Step 9: Designing the Page To add controls to the page, you can drag and drop them from the Toolbox onto the Web Form in Design mode. Like the Web Form itself, each control is an object that has properties, methods and events. You can type text directly on a Web Form at the cursor location or insert HTML/XHTML elements using menu commands.

47 23.4 Your First Web Application (Cont.)
Controls and other elements are placed sequentially on a Web Form. The cursor indicates the point at which text and HTML/XHTML elements will be inserted. You can drop the control at a specific position within the existing elements and rearrange existing controls using drag-and-drop actions.

48 23.4 Your First Web Application (Cont.)
The positions of controls and other elements are relative to the Web Form’s upper-left corner. This type of layout is known as relative positioning. An alternate type of layout is known as absolute positioning, in which controls are located exactly where they are dropped on the Web Form You can enable absolute positioning in Design mode in the HTML Designer > CSS Styling node of the Options dialog.

49 23.4 Your First Web Application (Cont.)
Portability Tip 23.2 Absolute positioning is discouraged, because pages designed in this manner may not render correctly in different browsers or on computers with different screen resolutions and font sizes. This could cause absolutely positioned elements to overlap each other or display off-screen, requiring the client to scroll to see the full page content.

50 23.4 Your First Web Application (Cont.)
To add the text to the Web Form, click within the gray rectangle at the top of the Web Form in Design mode. Type Current time on the web server:. Visual Web Developer is a WYSIWYG (What You See Is What You Get) editor—the IDE converts changes made in Design mode into markup. Highlight the text you added. From the Block Format drop-down list, choose Heading 2. Finally, click to the right of the text and press the Enter key to move the cursor to a new paragraph. The IDE should now look like Fig. 23.15.

51 23.4 Your First Web Application (Cont.)
Block Format drop-down list Cursor position after inserting a new paragraph by pressing Enter Fig | WebTime.aspx after inserting text and a new paragraph.

52 23.4 Your First Web Application (Cont.)
Place a Label on a Web Form either by dragging and dropping or by double clicking the Toolbox’s Label control. Using the Properties window, set the (ID) property of the Label to timeLabel. Delete timeLabel’s text, because we set it programmatically in the code-behind file. When a Label does not contain text, the name is displayed in square brackets in the Web Forms Designer (Fig. 23.16).

53 23.4 Your First Web Application (Cont.)
Set timeLabel’s BackColor, ForeColor and Font-Size properties to Black, Yellow and XX-Large, respectively or use the embedded CSS – see steps on p.910 Set the Label’s EnableViewState property to False. Finally, select DOCUMENT from the drop-down list in the Properties window and set the Web Form’s Enable­SessionState property to False.

54 23.4 Your First Web Application (Cont.)
Label Fig | WebTime.aspx after adding a Label and setting its properties.

55 23.4 Your First Web Application (Cont.)
Step 10: Adding Page Logic Open WebTime.aspx.cs by double clicking its node in the Solution Explorer. Add a Page_Init event handler to the code-behind file by renaming Page_Load Page_Init programmatically sets the text of time­Label to the current time on the server.

56 23.4 Your First Web Application (Cont.)
Step 11: Running the Program You can view the Web Form several ways. You can select Debug > Start Without Debugging, which runs the application by opening it in a browser window. To debug your application, you can select Debug > Start Debugging. You cannot debug a web application unless debugging is explicitly enabled by the web.config file. To view a specific ASPX file, you can right click either the Web Forms Designer or the ASPX file name and select View In Browser. Finally, you can run your application by opening a browser window and typing the web page’s URL in the Address field.

57 23.4 Your First Web Application (Cont.)
ASP.NET compiles your web page whenever it changes between HTTP requests. You can manually compile a web page or an entire website by selecting Build Page or Build Site, respectively, from the Build menu.

58 23.4 Your First Web Application (Cont.)
Windows Firewall Settings For security reasons, Windows Firewall does not allow remote access to a web server on your local computer by default. You can change this using the Windows Firewall utility in the Windows Control Panel.

59 Text and Graphics Control
23.5 Web Controls Text and Graphics Control Label, Button, TextBox, Image RadioButtonList and DropDownList AdRotator Control Randomly selects an image to display and then generates a hyperlink to the Web page associated with that image Validation Controls Determines whether the data in another Web control are in the proper format Validates user input

60 Fig. 23. 21 | Commonly used web controls.
Figure 23.21 summarizes several web controls. Fig | Commonly used web controls.

61 Fig. 23.18 | Web Form that demonstrates web controls. (Part 1 of 6. )
Outline Figure 23.18 depicts a simple form for gathering user input. WebControls.aspx ( 1 of 6 ) In the head element of your .aspx file, the style element defines embedded style sheets. Fig | Web Form that demonstrates web controls. (Part 1 of 6. )

62 Fig. 23.18 | Web Form that demonstrates web controls. (Part 2 of 6. )
WebControls.aspx ( 2 of 6 ) In the head element of your .aspx file, the style element defines embedded style sheets. An Image control inserts an image into a web page. A TextBox control allows you to obtain text from the user and display text to the user. Fig | Web Form that demonstrates web controls. (Part 2 of 6. )

63 Fig. 23.18 | Web Form that demonstrates web controls. (Part 3 of 6. )
Outline WebControls.aspx ( 3 of 6 ) Fig | Web Form that demonstrates web controls. (Part 3 of 6. )

64 Fig. 23.18 | Web Form that demonstrates web controls. (Part 4 of 6. )
WebControls.aspx ( 4 of 6 ) A TextBox control allows you to obtain text from the user and display text to the user. The HyperLink control adds a hyperlink to a web page. Fig | Web Form that demonstrates web controls. (Part 4 of 6. )

65 Fig. 23.18 | Web Form that demonstrates web controls. (Part 5 of 6. )
WebControls.aspx ( 5 of 6 ) The RadioButtonList control provides a series of radio buttons from which the user can select only one. A Button web control represents a button that triggers an action when clicked, and typically maps to an HTML/XHTML input element of type "button". Fig | Web Form that demonstrates web controls. (Part 5 of 6. )

66 Fig. 23.22 | Web Form that demonstrates web controls. (Part 6 of 6. )
Outline WebControls.aspx ( 6 of 6 ) Image control TextBox control DropDownList control HyperLink control RadioButtonList Button control Fig | Web Form that demonstrates web controls. (Part 6 of 6. )

67 23.5  Web Controls (Cont.) The code in Fig. 23.22 was generated by Visual Web Developer using Design mode. • To begin, create an ASP.NET Web Site named WebControls. • The page contains an h3 heading element, followed by a series of additional HTML/XHTML blocks. . • We use an HTML/XHTML table element to organize the Image and TextBox controls in the user-information section of the page.

68 Adding an HTML/XHTML Table to a Web Form
23.5  Web Controls (Cont.) Adding an HTML/XHTML Table to a Web Form Select Insert Table from the Table menu to display the Insert Table dialog (Fig. 23.23). 23g | Insert Table dialog.

69 23.5  Web Controls (Cont.) In the Size group box, change the values of Rows and Columns to 2. • Click OK to close the Insert Table dialog and create the table.

70 23.5  Web Controls (Cont.) We changed the vertical alignment of all cells in the table (i.e., td elements) by setting the valign property to top in the Properties window. We also changed the width of the cells in the left column by modifying the style property in the Properties window. Click the ellipsis next to the style property to display the Modify Style dialog. In this case, we set the width (in the Position category) to 225px.

71 23.5  Web Controls (Cont.) Setting the Color of Text on a Web Form To set the color of a specific piece of text, highlight the text and select Format > Font…. In the Font dialog that appears, choose a color or click More Colors…. he More Colors dialog offers a greater selection of colors and allows you to specify a custom color by clicking the Colors… button. The IDE places the colored text in an HTML span element and applies the color using CSS styling.

72 23.5  Web Controls (Cont.) Examining Web Controls on a Sample Registration Form An Image control inserts an image into a web page. We added an Images folder to this project by right clicking the location of the project in the Solution Explorer and selecting New Folder. We then added each of the images used in the example to this folder by right clicking the folder and selecting Add Existing Item…. The ImageUrl property specifies the location of the image to display.

73 23.5  Web Controls (Cont.) To select an image, click the ellipsis next to the ImageUrl property and use the Select Image dialog. A TextBox control allows you to obtain text from the user and display text to the user.

74 23.5  Web Controls (Cont.) A DropDownList is similar to the Windows Forms ComboBox control. However, a DropDownList does not allow users to type text. Each item in the drop-down list is defined by a ListItem element. You can add items to a DropDownList using the ListItem Collection Editor. This process is similar to customizing a ListBox in a Windows application. Visual Web Developer displays smart-tag menus for many ASP.NET controls to facilitate common tasks.

75 Fig. 23.24 | DropDownList Tasks smart-tag menu.
23.5  Web Controls (Cont.) Fig | DropDownList Tasks smart-tag menu.

76 Image control TextBox control DropDownList control Hyperlink control RadioButtonList control Button control

77 23.6 Validation Controls Validators
Determine if data in Web controls are proper format e.g. whether a phone contains 7 digits in the form: once the ph. # is submitted, the Web server responds with an HTML page containing all possible letter combinations that represent the phone # the 5 button represents the letters j, k and l

78 23.6 Validation Controls (Cont.)
TA validation control (or validator) determines whether the data in another web control is in the proper format, before the data is processed. When the HTML for our page is created, the validator is converted into JavaScript that performs the validation. JavaScript is a scripting language that enhances the functionality and appearance of web pages and is typically executed on the client. Because some clients disable or do not support scripting, ASP.NET validation controls can function on the client, on the server or both.

79 Validating Input in a Web Form Figure 23.22 presents the ASPX file.
Outline Validating Input in a Web Form Figure 23.22 presents the ASPX file. Validation.aspx ( 1 of 7 ) Fig | Validators used in a Web Form that retrieves user contact information. (Part 1 of 7. )

80 Validation.aspx (2 of 7 ) The Control­ToValidate property indicates which control’s contents is verified by the RequiredFieldValidator. Property ErrorMessage’s text is displayed on the Web Form if the validation fails. Because we set the validator’s Display property to Dynamic, the validator is displayed on the Web Form only when validation fails. Fig | Validators used in a Web Form that retrieves user contact information. (Part 2 of 7. )

81 Outline Validation.aspx ( 3 of 7 )
Fig | Validators used in a Web Form that retrieves user contact information. (Part 3 of 7. )

82 Outline Validation.aspx (4 of 7 )
Fig | Validators used in a Web Form that retrieves user contact information. (Part 4 of 7. )

83 Outline Validation.aspx (5 of 7 )
outputLabel’s Visible property is initially set to False (line 87), so it won’t appear in the browser when the page first loads. a) Fig | Validators used in a Web Form that retrieves user contact information. (Part 5 of 7. )

84 Outline Validation.aspx (6 of 7 )
b) Validation.aspx (6 of 7 ) c) Fig | Validators used in a Web Form that retrieves user contact information. (Part 6 of 7. )

85 Outline Validation.aspx ( 1 of 7 )
Fig | Validators used in a Web Form that retrieves user contact information. (Part 1 of 7. )

86 23.6 Validation Controls (Cont.)
Using RequiredFieldValidator Controls A RequiredFieldValidator makes an input control a required field. If such a field is empty, validation fails. The ControlToValidate property indicates which control’s contents is verified by the RequiredFieldValidator. Set the value of this property (and the validator’s other properties) to nameTextBox’s content by selecting the validator in Design mode and using the Properties window.

87 23.6 Validation Controls (Cont.)
Property ErrorMessage’s text is displayed on the Web Form if the validation fails. Because we set the validator’s Display property to Dynamic, the validator is displayed on the Web Form only when validation fails. The controls below the validator shift downward to accommodate the ErrorMessage, as seen in Fig. 23.22(b).

88 23.6 Validation Controls (Cont.)
Using RegularExpressionValidator Controls This example also uses RegularExpressionValidator controls to match the address and phone number against regular expressions. A RegularExpressionValidator’s ValidationExpression property specifies the regular expression that validates the ControlToValidate’s contents. Clicking the ellipsis next to ValidationExpression in the Properties window displays the Regular Expression Editor dialog.

89 23.6 Validation Controls (Cont.)
The Regular Expression Editor contains a list of Standard expressions for phone numbers, zip codes and other formatted information. If the user enters an invalid address and clicks in a different text box or attempts to submit the form, the ErrorMessage text is displayed in red. If all five validators are successful, clicking the Submit button sends the form’s data to the server. The server then responds by displaying the submitted data in the outputLabel.

90 Examining the Code-Behind File for a Web Form That Receives User Input
Outline Examining the Code-Behind File for a Web Form That Receives User Input Figure 23.23 depicts the code-behind file for the ASPX file in Fig. 23.22. Validation.aspx .cs ( 1 of 2 ) The IsPostBack property of class Page determines whether the page is being loaded due to a postback. Always first the current Page’s Validate method validates the information as specified by the validation controls in the Web Form on the Server-Side Web Form Fig | Code-behind file for a Web Form that obtains a user’s contact information. (Part 1 of 2. )

91 Outline Validation.aspx .cs ( 2 of 2 )
Use the IsValid property of class Page to check whether all the validators succeeded. Fig | Code-behind file for a Web Form that obtains a user’s contact information. (Part 2 of 2. )

92 23.6 Validation Controls (Cont.)
The code-behind file validates the information again in case the client has JavaScript disabled. The submission of a form sends its data to the server and causes the current page to be requested again is called a postback. The IsPostBack property of class Page determines whether the page is being loaded due to a postback IsPostBack = false if the 1st time the Web is requested, otherwise is true. The current Page’s Validate method validates the information as specified by the validation controls in the Web Form.

93 23.6 Validation Controls (Cont.)
Use the IsValid property of class Page to check whether all the validators succeeded. You should always call method Validate before using property IsValid. When data is posted to the web server, the form’s data becomes accessible to the web application through the properties of the various web controls.

94 23.6 Validation Controls (Cont.)
Examining the Client-Side HTML for a Web Form with Validation If a validation control’s EnableClientScript property is True, the validator performs client-side validation as the user edits the Web Form. You do not need to be able to create or even understand the JavaScript validation code - the validators are converted to working JavaScript by ASP.NET.

95 23.6 Validation Controls (Cont.)
The EnableViewState attribute determines whether a web control’s current state is remembered each time a postback occurs. The default value, True, indicates that the control’s state at the last postback is retained. A hidden input called __VIEWSTATE stores the controls’ data as an encoded string so the server can determine whether it has changed. Performance Tip 23.1 Setting EnableViewState to False reduces the amount of data passed to the web server with each request.

96 23.7 Session Tracking Personalization Privacy protection
Tailored to client’s needs Customer loyalty Session ID Privacy protection Release of vital possibly private data

97 Cookies Cookies Text file stored by a Web site on a individual’s computer that allows the site to track the actions of the visitor Records sites that the user visits and identifies shopping preferences Cookies can store name-value pairs Web Server can never access cookies created outside the domain associated with that server

98 OptionsPage.aspx Label Web control
1 <%-- Fig : OptionsPage.aspx %> 2 <%-- This ASPX page allows the user to choose a language. --%> 3 4 Page language="c#" Codebehind="OptionsPage.aspx.cs" AutoEventWireup="false" Inherits="Cookies.OptionsPage" %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 9 10 <HTML> <HEAD> <title>RecommendationsPage</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content= "JavaScript"> <meta name="vs_targetSchema" content= " </HEAD> 21 <body> <form id="RecommendationsPage" method="post" runat="server"> <P> <asp:Label id="promptLabel" runat="server" Font-Bold="True">Select a programming language: </asp:Label> 29 <asp:Label id="welcomeLabel" runat="server" Font-Bold="True" Visible="False"> Welcome to Cookies! You selected </asp:Label> </P> 35 OptionsPage.aspx Label Web control

99 Defines five radio buttons
<P> <asp:RadioButtonList id="languageList" runat= "server"> <asp:ListItem Value="C#">C#</asp:ListItem> 40 <asp:ListItem Value="C++">C++</asp:ListItem> 42 <asp:ListItem Value="C">C</asp:ListItem> 44 <asp:ListItem Value="Python">Python </asp:ListItem> 47 <asp:ListItem Value="Visual Basic .NET"> Visual Basic .NET </asp:ListItem> </asp:RadioButtonList> </P> 53 <P> <asp:Button id="submitButton" runat="server" Text= "Submit"> </asp:Button> </P> 59 <P> <asp:HyperLink id="languageLink" runat="server" NavigateUrl="OptionsPage.aspx" Visible="False"> Click here to choose another language. </asp:HyperLink> </P> 66 <P> <asp:HyperLink id="recommendationsLink" runat= "server" NavigateUrl="RecommendationsPage.aspx" Defines five radio buttons OptionsPage.aspx Request current page, does not cause a postback

100 70 Visible="False">Click here to get book recommendations.
</asp:HyperLink> </P> </form> </body> 75 </HTML> OptionsPage.aspx

101 Define books as a Hashtable, stores key-value
1 // Fig : OptionPage.aspx.cs 2 // A listing of program languages that the user can choose from. 3 4 using System; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Data; 8 using System.Drawing; 9 using System.Web; 10 using System.Web.SessionState; 11 using System.Web.UI; 12 using System.Web.UI.WebControls; 13 using System.Web.UI.HtmlControls; 14 15 namespace Cookies 16 { // page contains language options in a RadioButtonList, // will add a cookie to store their choice public class OptionsPage : System.Web.UI.Page { protected System.Web.UI.WebControls.Label promptLabel; protected System.Web.UI.WebControls.Label welcomeLabel; 23 protected System.Web.UI.WebControls.RadioButtonList languageList; 26 protected System.Web.UI.WebControls.HyperLink languageLink; protected System.Web.UI.WebControls.HyperLink recommendationsLink; 31 protected System.Web.UI.WebControls.Button submitButton; 34 protected Hashtable books = new Hashtable(); OptionsPage.aspx.cs Define books as a Hashtable, stores key-value

102 Two hyperlinks are made visible
36 // event handler for Load event private void Page_Load( object sender, System.EventArgs e ) { if ( IsPostBack ) { // if postback has occurred, user has submitted // information, so display welcome message // and appropriate hyperlinks welcomeLabel.Visible = true; languageLink.Visible = true; recommendationsLink.Visible = true; 49 // hide option information submitButton.Visible = false; promptLabel.Visible = false; languageList.Visible = false; 54 // notify user of what they have chosen if ( languageList.SelectedItem != null ) welcomeLabel.Text += languageList.SelectedItem.ToString() + "."; else welcomeLabel.Text += "no language."; 61 } // end if 63 } // end method Page_Load 65 OptionsPage.aspx.cs Two hyperlinks are made visible Determines whether the user selected a language

103 Returns value corresponding to key contained in language
override protected void OnInit( EventArgs e ) { // add values to Hashtable books.Add( "C#", " " ); books.Add( "C++", " " ); books.Add( "C", " " ); books.Add( "Python", " " ); books.Add( "Visual Basic .NET", " " ); 74 InitializeComponent(); base.OnInit( e ); } 78 // Visual Studio .NET generated code 80 // when user clicks Submit button // create cookie to store user's choice private void submitButton_Click( object sender, System.EventArgs e ) { // if choice was made by user if ( languageList.SelectedItem != null ) { string language = languageList.SelectedItem.ToString(); 91 string ISBN = books[ language ].ToString(); 93 // create cookie, name-value pair is // language chosen and ISBN number from Hashtable HttpCookie cookie = new HttpCookie( language, ISBN ); 98 OptionsPage.aspx.cs Returns value corresponding to key contained in language New cookie object created to store language and ISBN number

104 99 // add cookie to response,
// thus placing it on user's machine Response.Cookies.Add( cookie ); 102 } // end if 104 } // end method submitButton_Click 106 } // end class OptionsPage 108 109 } // end namespace Cookies Cookie is added to the cookie collection sent as part of HTTP response header OptionsPage.aspx.cs

105 OptionsPage.aspx.cs Program Output

106 Label displays text recommendations
1 <%-- Fig : RecommendationsPage.aspx --%> 2 <%-- This page shows recommendations %> 3 <%-- retrieved from the Hashtable %> 4 5 Page language="c#" Codebehind="RecommendationsPage.aspx.cs" AutoEventWireup="false" Inherits="Cookies.RecommendationsPage" %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 10 11 <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content= " </HEAD> 21 <body MS_POSITIONING="GridLayout"> 23 <form id="Form1" method="post" runat="server"> 25 <asp:Label id="recommendationsLabel" style="Z-INDEX: 101; LEFT: 21px; POSITION: absolute; TOP: 25px" runat="server" Font-Bold="True" Font-Size="X-Large">Recommendations </asp:Label> 31 <asp:ListBox id="booksListBox" style="Z-INDEX: 102; LEFT: 21px; POSITION: absolute; TOP: 82px" runat= "server" Width="383px" Height="91px"> </asp:ListBox> RecommendationsPage.aspx Label displays text recommendations Displays the recommendations created by the code-behind file

107 36 </form> 37 </body> 38 </HTML>
RecommendationsPage.aspx

108 Method to retrieve cookies from the client
1 // Fig 20.27: RecommendationsPage.aspx.cs 2 // Reading cookie data from the client. 3 4 using System; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Data; 8 using System.Drawing; 9 using System.Web; 10 using System.Web.SessionState; 11 using System.Web.UI; 12 using System.Web.UI.WebControls; 13 using System.Web.UI.HtmlControls; 14 15 namespace Cookies 16 { // page displays cookie information and recommendations public class RecommendationsPage : System.Web.UI.Page { protected System.Web.UI.WebControls.ListBox booksListBox; protected System.Web.UI.WebControls.Label recommendationsLabel; 23 // Visual Studio .NET generated code 25 override protected void OnInit( EventArgs e ) { InitializeComponent(); base.OnInit( e ); 30 // retrieve client's cookies HttpCookieCollection cookies = Request.Cookies; 33 RecommendationsPage.aspx.cs Method to retrieve cookies from the client

109 Ensure that there is at least one cookie besides ASP.NET_SessionID
// if there are cookies other than the ID cookie, // list appropriate books and ISBN numbers if ( cookies != null && cookies.Count != 1 ) for ( int i = 1; i < cookies.Count; i++ ) booksListBox.Items.Add( cookies[ i ].Name + " How to Program. ISBN#: " + cookies[ i ].Value ); 42 // if no cookies besides ID, no options were // chosen, so no recommendations made else { recommendationsLabel.Text = "No Recommendations."; booksListBox.Items.Clear(); booksListBox.Visible = false; } 51 } // end method OnInit 53 } // end class RecommendationsPage 55 56 } // end namespace Cookies Determine whether at least two cookies exist RecommendationsPage.aspx.cs Add information in other cookies into list box Execute if no language was selected

110 RecommendationsPage.aspx.cs Program Output

111 Cookies

112 23.7.2 Session Tracking with HttpSessionState
HttpSessionState objects can store any type of objects (not just Strings) as attribute values

113 OptionsPage.aspx 1 <%-- Fig. 20.29: OptionsPage.aspx --%>
2 <%-- Page that presents a list of language options. --%> 3 4 Page language="c#" Codebehind="OptionsPage.aspx.cs" AutoEventWireup="false" Inherits= "Sessions.OptionsPage" %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 9 <HTML> <HEAD> <title>RecommendationsPage</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema" content= " </HEAD> 19 <body> <form id="RecommendationsPage" method="post" runat="server"> <P> <asp:Label id="promptLabel" runat="server" Font-Bold="True">Select a programming language: </asp:Label> 27 <asp:Label id="welcomeLabel" runat="server" Font-Bold="True" Visible="False"> Welcome to Cookies! You selected </asp:Label> </P> 33 <P> OptionsPage.aspx

114 OptionsPage.aspx 35 <asp:RadioButtonList id="languageList" runat=
"server"> 37 <asp:ListItem Value="C#">C#</asp:ListItem> 39 <asp:ListItem Value="C++">C++</asp:ListItem> 41 <asp:ListItem Value="C">C</asp:ListItem> 43 <asp:ListItem Value="Python">Python </asp:ListItem> 46 <asp:ListItem Value="Visual Basic .NET"> Visual Basic .NET </asp:ListItem> </asp:RadioButtonList> </P> 52 <P> <asp:Button id="submitButton" runat="server" Text="Submit"> </asp:Button> </P> 58 <P> <asp:Label id="idLabel" runat="server"> </asp:Label> </P> 63 <P> <asp:Label id="timeoutLabel" runat="server"> </asp:Label> </P> 68 <P> OptionsPage.aspx

115 70 <asp:Label id="newSessionLabel" runat="server">
73 <P> <asp:HyperLink id="languageLink" runat="server" NavigateUrl="OptionsPage.aspx" Visible="False"> Click here to choose another language. </asp:HyperLink> </P> 80 <P> <asp:HyperLink id="recommendationsLink" runat= "server" NavigateUrl="RecommendationsPage.aspx" Visible="False"> Click here to get book recommendations. </asp:HyperLink> </P> </form> </body> 90 </HTML> OptionsPage.aspx

116 OptionsPage.aspx.cs 1 // Fig. 20.30: OptionsPage.aspx.cs
2 // A listing of programming languages, 3 // choice is stored in page’s Session object. 4 5 using System; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Data; 9 using System.Drawing; 10 using System.Web; 11 using System.Web.SessionState; 12 using System.Web.UI; 13 using System.Web.UI.WebControls; 14 using System.Web.UI.HtmlControls; 15 16 namespace Sessions 17 { // page contains language options in a RadioButtonList // will add cookie to store user’s choice public class OptionsPage : System.Web.UI.Page { protected System.Web.UI.WebControls.Label promptLabel; protected System.Web.UI.WebControls.Label welcomeLabel; protected System.Web.UI.WebControls.Label idLabel; protected System.Web.UI.WebControls.Label timeoutLabel; 26 protected System.Web.UI.WebControls.HyperLink languageLink; protected System.Web.UI.WebControls.HyperLink recommendationsLink; 31 protected System.Web.UI.WebControls.RadioButtonList languageList; protected System.Web.UI.WebControls.Button submitButton; 35 OptionsPage.aspx.cs

117 SessionID contains session’s unique ID
private Hashtable books = new Hashtable(); 37 // event handler for Load event private void Page_Load( object sender, System.EventArgs e ) { // if page is loaded due to postback, load session // information, hide language options from user if ( IsPostBack ) { // display components that contain session information welcomeLabel.Visible = true; languageLink.Visible = true; recommendationsLink.Visible = true; 50 // hide components submitButton.Visible = false; promptLabel.Visible = false; languageList.Visible = false; 55 // set labels to display Session information if ( languageList.SelectedItem != null ) welcomeLabel.Text += languageList.SelectedItem.ToString() + "."; else welcomeLabel.Text += "no language."; 62 idLabel.Text += "Your unique session ID is: " + Session.SessionID; 65 timeoutLabel.Text += "Timeout: " + Session.Timeout + " minutes"; 68 } // end if 70 OptionsPage.aspx.cs Specify maximum amount of time that an HttpSessionState object can be inactive before discarded SessionID contains session’s unique ID

118 71 } // end method Page_Load
72 override protected void OnInit( EventArgs e ) { // add values to Hashtable books.Add( "C#", " " ); books.Add( "C++", " " ); books.Add( "C", " " ); books.Add( "Python", " " ); books.Add( "Visual Basic .NET", " " ); 81 InitializeComponent(); base.OnInit( e ); } 85 // Visual Studio .NET generated code 87 // when user clicks Submit button, // store user's choice in session object private void submitButton_Click( object sender, System.EventArgs e ) { if ( languageList.SelectedItem != null ) { string language = languageList.SelectedItem.ToString(); string ISBN = books[ language ].ToString(); 98 // store in session object as name-value pair // name is language chosen, value is // ISBN number for corresponding book Session.Add( language, ISBN ); 103 } // end if OptionsPage.aspx.cs Method Add to place language and its corresponding recommended book’s ISBN into HttpSessionState object

119 OptionsPage.aspx.cs 105 106 } // end method submitButton_Click 107
} // end class OptionsPage 109 110 } // end namespace Sessions OptionsPage.aspx.cs

120 OptionsPage.aspx.cs Program Output

121 23.7.2 Session Tracking with HttpSessionState

122 ListBox Web control that is used to present recommendations to user
1 <%-- Fig : RecommendationsPage.aspx --%> 2 <%-- Read the user's session data %> 3 4 Page language="c#" Codebehind="RecommendationsPage.aspx.cs" AutoEventWireup="false" Inherits="Sessions.RecommendationsPage" %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > 9 10 <HTML> <HEAD> <title>WebForm1</title> <meta name="GENERATOR" Content= "Microsoft Visual Studio 7.0"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name="vs_defaultClientScript" content= "JavaScript"> <meta name="vs_targetSchema" content= " </HEAD> 21 <body MS_POSITIONING="GridLayout"> <form id="Form1" method="post" runat="server"> <asp:Label id="recommendationsLabel" style="Z-INDEX: 101; LEFT: 21px; POSITION: absolute; TOP: 25px" runat="server" Font-Bold="True" Font-Size="X-Large">Recommendations </asp:Label> 29 <asp:ListBox id="booksListBox" style="Z-INDEX: 102; LEFT: 21px; POSITION: absolute; TOP: 84px" runat= "server" Width="383px" Height="91px"> </asp:ListBox> RecommendationsPage.aspx ListBox Web control that is used to present recommendations to user

123 34 </form> 35 </body> 36 </HTML>
RecommendationsPage.aspx

124 Event handler OnInit retrieves session information
1 // Fig : RecommendationsPage.aspx.cs 2 // Reading session data from the user. 3 4 using System; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Data; 8 using System.Drawing; 9 using System.Web; 10 using System.Web.SessionState; 11 using System.Web.UI; 12 using System.Web.UI.WebControls; 13 using System.Web.UI.HtmlControls; 14 15 namespace Sessions 16 { // page displaying session information and recommendations public class RecommendationsPage : System.Web.UI.Page { protected System.Web.UI.WebControls.ListBox booksListBox; 21 protected System.Web.UI.WebControls.Label recommendationsLabel; 24 // Visual Studio .NET generated code 26 // event handler for Init event override protected void OnInit( EventArgs e ) { InitializeComponent(); base.OnInit( e ); 32 RecommendationsPage.aspx.cs Event handler OnInit retrieves session information

125 Iterates through the Session object
// determine if Session contains information if ( Session.Count != 0 ) { // iterate through Session values, // display in ListBox for ( int i = 0; i < Session.Count; i++ ) { // store current key in sessionName string keyName = Session.Keys[ i ]; 42 // use current key to display // Session's name/value pairs booksListBox.Items.Add( keyName + " How to Program. ISBN#: " + Session[ keyName ] ); 48 } // end for 50 } else { recommendationsLabel.Text = "No Recommendations"; booksListBox.Visible = false; } 57 } // end method OnInit 59 } // end class RecommendationsPage 61 62 } // end namespace Sessions RecommendationsPage.aspx.cs Iterates through the Session object Indexing the Session object with key name If no language was ever selected

126 RecommendationsPage.aspx.cs Program Output

127 23.8 Case Study: Connecting to a Database in ASP.NET
In this section, we create a guestbook Web Form application. This example’s GUI contains a GridView ASP.NET data control, as shown in Fig. 23.31, which displays all the entries in the guestbook in tabular format. GridView control Fig | Guestbook application GUI in Design mode.

128 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
The application stores the guestbook information in a SQL Server database called Guestbook.mdf located on the web server. Below the HTML form, the GridView displays the data in the database’s Messages table.

129 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
23.8.1 Building a Web Form That Displays Data from a Database Step 1: Creating the Project Create an ASP.NET Web Site named Guestbook and name the ASPX file Guestbook.aspx. Rename the class in the code-behind file Guestbook, and update the Page directive in the ASPX file accordingly.

130 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
Step 2: Creating the Form for User Input In Design mode for the ASPX file, add the text Please leave a message in our guestbook: formatted as an h2 header. Insert an HTML/XHTML table with two columns and four rows. Place the appropriate text in the top three cells in the table’s left column.

131 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
Place TextBoxes called nameTextBox, TextBox and messageTextBox in the top three cells in the right column, and give them width 300px. Set messageTextBox to be a multiline TextBox by the setting the TextMode property to MultiLine. Add Buttons named submitButton and clearButton to the bottom-right table cell. Set the buttons’ Text properties to Submit and Clear, respectively.

132 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
Step 3: Adding a GridView Control to the Web Form Add a GridView named messagesGridView that will display the guestbook entries. The colors for the GridView are specified through the Auto Format... link in the GridView Tasks smart-tag menu. In this example, we chose Simple.

133 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
Step 4: Adding a Database to an ASP.NET Web Application Right click the project’s App_Data folder in the Solution Explorer and select Add Existing Item…. Locate the Guestbook.mdf and click Add. Right click the project and select Add New Item…; select LINQ to SQL Classes, enter GuestbookDB.dbml as the Name, and click Add. Click Yes to put your new LINQ to SQL classes in the App_Code folder Drag the Guestbook database’s Messages table from the Database Explorer onto the Object Relational Designer.

134 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
Step 5: Binding the GridView to the Messages Table of the Guestbook Database Open the GridView Tasks smart-tag menu, then select <New data source...> from the Choose Data Source drop-down list. In the Data Source Configuration Wizard that appears, select LINQ. In this example, we use a LinqDataSource control that allows the application to interact with the Guestbook.mdf database through LINQ. Set the ID of the data source to messagesLinqDataSource and click OK to begin the Configure Data Source wizard.

135 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
In the Choose a Context Object screen, select GuestbookDBDataContext from the drop-down list (Fig. 23.35), then click Next >. Fig | Configure Data Source dialog in Visual Web Developer.

136 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
The Configure Data Selection step (Fig. 23.36) allows you to specify which data the LinqDataSource should retrieve from the data context. Fig | Configuring the query used by the LinqDataSource to retrieve data Your choices on this page design a select LINQ query.

137 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
In the Select pane, select the checkbox marked with an asterisk (*) to indicate that you want to retrieve all the columns in the Messages table. Click the Advanced… button, then check the box next to Enable the LinqDataSource to perform automatic inserts. Click Finish. A control named messagesLinqDataSource now appears on the Web Form directly below the GridView (Fig. 23.37).

138 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
LinqDataSource control Fig | Design mode displaying LinqDataSource control for a GridView. It will not appear on the web page at runtime—the gray box simply provides a way to manipulate the control visually through Design mode.

139 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
Step 6: Modifying the Columns of the Data SourceDisplayed in the GridView In the GridView Tasks smart-tag menu, click Edit Columns. In the resulting Fields dialog (Fig. 23.35), select MessageID in the Selected fields pane, then click the Delete button ( ).

140 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
Fig | Removing the MessageID column from the GridView. Select the MessageText field and change the HeaderText property to Message.

141 Fig. 23.39 | ASPX file for the guestbook application. (Part 1 of 7.)
Outline ASPX File for a Web Form That Interacts with a Database The ASPX file generated by the guestbook GUI and messagesLinqDataSource control is shown below Guestbook.aspx (1 of 7 ) Fig | ASPX file for the guestbook application. (Part 1 of 7.)

142 Fig. 23.39 | ASPX file for the guestbook application. (Part 2 of 7.)
Outline Guestbook.aspx (2 of 7 ) Fig | ASPX file for the guestbook application. (Part 2 of 7.)

143 Fig. 23.39 | ASPX file for the guestbook application. (Part 3 of 7.)
Outline Guestbook.aspx (3 of 7 ) Fig | ASPX file for the guestbook application. (Part 3 of 7.)

144 Fig. 23.39 | ASPX file for the guestbook application. (Part 4 of 7.)
Outline Guestbook.aspx (4 of 7 ) The <asp:GridView> start tag sets various GridView properties. The DataSource­ID property identifies the data source that is used to fill the GridView with data at runtime. Each column is represented as a BoundField, because the values in the columns are bound to data in the data source. Fig | ASPX file for the guestbook application. (Part 4 of 7.)

145 Fig. 23.39 | ASPX file for the guestbook application. (Part 5 of 7.)
Outline Guestbook.aspx (5 of 7 ) The LinqDataSource’s ContextTypeName property indicates the data context that the LinqDataSource interacts with. The TableName property in line 91 specifies the table from which to retrieve data. Fig | ASPX file for the guestbook application. (Part 5 of 7.)

146 Fig. 23.39 | ASPX file for the guestbook application. (Part 6 of 7.)
Outline a) Guestbook.aspx (6 of 7 ) Fig | ASPX file for the guestbook application. (Part 6 of 7.)

147 Fig. 23.39 | ASPX file for the guestbook application. (Part 7 of 7.)
Outline b) Guestbook.aspx (7 of 7 ) Fig | ASPX file for the guestbook application. (Part 7 of 7.)

148 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
The <asp:GridView> start tag sets various GridView properties. The DataSource­ID property identifies the data source that is used to fill the GridView with data at runtime. Each column is represented as a BoundField, because the values in the columns are bound to data in the data source. Property DataField of each BoundField identifies the column in the data source to which a GridView column is bound.

149 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
The SortExpression property specifies the expression used to sort the GridView’s elements when the user chooses to sort by the column. The LinqDataSource’s ContextTypeName property indicates the data context that the LinqDataSource interacts with. The TableName property in line 91 specifies the table from which to retrieve data.

150 Outline Double click the Submit and Clear buttons in Design view to create their corresponding Click event handlers in the code-behind file (Fig. 23.40). Guestbook.aspx.cs (1 of 2 ) Fig | Code-behind file for the guestbook application. (Part 1 of 2.)

151 Outline Guestbook.aspx.cs (2 of 2 )
Invoking the LinqDataSource method Insert executes the insert LINQ command to add a row to the Messages table. Invoke messagesGridView’s DataBind method to refresh the data that the GridView displays. Clear each TextBox by setting its Text property to an empty string. Fig | Code-behind file for the guestbook application. (Part 2 of 2.)

152 23.8 Case Study: Connecting to a Database in ASP.NET (Cont.)
The IDE generates empty event handlers, so we must add the appropriate code to make these buttons work properly. Invoking the LinqDataSource method Insert executes the insert LINQ command to add a row to the Messages table. We pass the Dictionary object as an argument for the Insert method to specify the insert parameters. Invoke messagesGridView’s DataBind method to refresh the data that the GridView displays.


Download ppt " 2009 Pearson Education, Inc. All rights reserved."

Similar presentations


Ads by Google