Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition phần 10 ppsx

140 433 1
Pro C# 2008 and the .NET 3.5 Platform, Fourth Edition phần 10 ppsx

Đ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

To illustrate working with these validation controls, create a new Web Site project named ValidatorCtrls. To begin, place four (well-named) TextBox types (with four corresponding and descriptive Labels) onto your page. Next, place a RequiredFieldValidator, RangeValidator, RegularExpressionValidator, and CompareValidator type adjacent to each respective field. Finally, add a single Button and final Label (see Figure 32-18). Figure 32-18. Various validators Now that you have a UI, let’s walk through the process of configuring each member. The RequiredFieldValidator Configuring the RequiredFieldValidator is straightforward. Simply set the ErrorMessage and ControlToValidate properties accordingly using the Visual Studio 2008 Properties window. Here would be the resulting markup to ensure the txtRequiredField text box is not empty: <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtRequiredField" ErrorMessage="Oops! Need to enter data."> </asp:RequiredFieldValidator> The RequiredFieldValidator supports an InitialValue property. You can use this property to ensure that the user enters any value other than the initial value in the related TextBox. For example, when the user first posts to a page, you may wish to configure a TextBox to contain the value “Please enter your name”. Now, if you did not set the InitialValue property of the RequiredFieldValidator, the runtime would assume that the string “Please enter your name” is valid. Thus, to ensure a required TextBox is valid only when the user enters anything other than “Please enter your name”, configure your widgets as follows: CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES1232 8849CH32.qxd 10/16/07 12:51 PM Page 1232 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtRequiredField" ErrorMessage="Oops! Need to enter data." InitialValue="Please enter your name"> </asp:RequiredFieldValidator> The RegularExpressionValidator The RegularExpressionValidator can be used when you wish to apply a pattern against the charac- ters entered within a given input field. To ensure that a given TextBox contains a valid US Social Security number, you could define the widget as follows: <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtRegExp" ErrorMessage="Please enter a valid US SSN." ValidationExpression="\d{3}-\d{2}-\d{4}"> </asp:RegularExpressionValidator> Notice how the RegularExpressionValidator defines a ValidationExpression property. If you have never worked with regular expressions before, all you need to be aware of for this example is that they are used to match a given string pattern. Here, the expression "\d{3}-\d{2}-\d{4}" is cap- turing a standard US Social Security number of the form xxx-xx-xxxx (where x is any digit). This particular regular expression is fairly self-explanatory; however, assume you wish to test for a valid Japanese phone number. The correct expression now becomes much more complex: "(0\d{1,4}-|\(0\d{1,4}\)?)?\d{1,4}-\d{4}". The good news is that when you select the ValidationExpression property using the Properties window, you can pick from a predefined set of common regular expressions by clicking the ellipse button. ■Note If you are interested in regular expressions, you will be happy to know that the .NET platform supplies two namespaces ( System.Text.RegularExpressions and System.Web.RegularExpressions) devoted to the pro- grammatic manipulation of such patterns. The RangeValidator In addition to a MinimumValue and MaximumValue property, RangeValidators have a property named Type. Because you are interested in testing the user-supplied input against a range of whole num- bers, you need to specify Integer (which is not the default!): <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtRange" ErrorMessage="Please enter value between 0 and 100." MaximumValue="100" MinimumValue="0" Type="Integer"> </asp:RangeValidator> The RangeValidator can also be used to test whether a given value is between a currency value, date, floating-point number, or string data (the default setting). The CompareValidator Finally, notice that the CompareValidator supports an Operator property: CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES 1233 8849CH32.qxd 10/16/07 12:51 PM Page 1233 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtComparison" ErrorMessage="Enter a value less than 20." Operator="LessThan" ValueToCompare="20"> </asp:CompareValidator> Given that the role of this validator is to compare the value in the text box against another value using a binary operator, it should be no surprise that the Operator property may be set to values such as LessThan, GreaterThan, Equal, and NotEqual. Also note that the ValueToCompare is used to establish a value to compare against. ■Note The CompareValidator can also be configured to compare a value within another Web Form control (rather than a hard-coded value) using the ControlToValidate property. To finish up the code for this page, handle the Click event for the Button type and inform the user he or she has succeeded in the validation logic: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnPostback_Click(object sender, EventArgs e) { lblValidationComplete.Text = "You passed validation!"; } } Now, navigate to this page using your browser of choice. At this point, you should not see any noticeable changes. However, when you attempt to click the Submit button after entering bogus data, your error message is suddenly visible. Once you enter valid data, the error messages are removed and postback occurs. If you look at the HTML rendered by the browser, you see that the validation controls generate a client-side JavaScript function that makes use of a specific library of JavaScript functions (con- tained in the WebUIValidation.js file) that is automatically downloaded to the user’s machine. Once the validation has occurred, the form data is posted back to the server, where the ASP.NET runtime will perform the same validation tests on the web server (just to ensure that no along-the-wire tam- pering has taken place). On a related note, if the HTTP request was sent by a browser that does not support client-side JavaScript, all validation will occur on the server. In this way, you can program against the validation controls without being concerned with the target browser; the returned HTML page redirects the error processing back to the web server. Creating Validation Summaries The next validation-centric topic we will examine here is the use of the ValidationSummary widget. Currently, each of your validators displays its error message at the exact place in which it was posi- tioned at design time. In many cases, this may be exactly what you are looking for. However, on a complex form with numerous input widgets, you may not want to have random blobs of red text pop up. Using the ValidationSummary type, you can instruct all of your validation types to display their error messages at a specific location on the page. CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES1234 8849CH32.qxd 10/16/07 12:51 PM Page 1234 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The first step is to simply place a ValidationSummary on your *.aspx file. You may optionally set the HeaderText property of this type as well as the DisplayMode, which by default will list all error messages as a bulleted list. <asp:ValidationSummary id="ValidationSummary1" runat="server" Width="353px" HeaderText="Here are the things you must correct."> </asp:ValidationSummary> Next, you need to set the Display property to None for each of the individual validators (e.g., RequiredFieldValidator, RangeValidator, etc.) on the page. This will ensure that you do not see duplicate error messages for a given validation failure (one in the summary pane and another at the validator’s location). Figure 32-19 shows the summary pane in action. Figure 32-19. Using a validation summary Last but not least, if you would rather have the error messages displayed using a client-side MessageBox, set the ShowMessageBox property to true and the ShowSummary property to false. Defining Validation Groups It is also possible to define groups for validators to belong to. This can be very helpful when you have regions of a page that work as a collective whole. For example, you may have one group of controls in a Panel object to allow the user to enter his or her mailing address and another Panel containing UI elements to gather credit card information. Using groups, you can configure each group of controls to be validated independently. Insert a new page into your current project named ValidationGroups.aspx that defines two Panels. The first Panel object expects a TextBox to contain some form of user input (via a RequiredFieldValidator), while the second Panel expects a US SSN value (via a RegularExpressionValidator). Figure 32-20 shows one possible UI. CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES 1235 8849CH32.qxd 10/16/07 12:51 PM Page 1235 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 32-20. These Panel objects will independently configure their input areas. To ensure that the validators function independently, simply assign each validator and the con- trol being validated to a uniquely named group using the ValidationGroup property. Here is some possible markup (note that the Click event handlers used here are essentially empty stubs in the code file, and they are only used to allow postback to occur to the web server): <form id="form1" runat="server"> <asp:Panel ID="Panel1" runat="server" Height="83px" Width="296px"> <asp:TextBox ID="txtRequiredData" runat="server" ValidationGroup="FirstGroup"> </asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*Required field!" ControlToValidate="txtRequiredData" ValidationGroup="FirstGroup"> </asp:RequiredFieldValidator> <asp:Button ID="bntValidateRequired" runat="server" OnClick="bntValidateRequired_Click" Text="Validate" ValidationGroup="FirstGroup" /> </asp:Panel> <asp:Panel ID="Panel2" runat="server" Height="119px" Width="295px"> <asp:TextBox ID="txtSSN" runat="server" ValidationGroup="SecondGroup"> </asp:TextBox> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtSSN" ErrorMessage="*Need SSN" ValidationExpression="\d{3}-\d{2}-\d{4}" ValidationGroup="SecondGroup"> </asp:RegularExpressionValidator>&nbsp; <asp:Button ID="btnValidateSSN" runat="server" OnClick="btnValidateSSN_Click" Text="Validate" ValidationGroup="SecondGroup" /> </asp:Panel> </form> Now, right-click this page’s designer and select the View In Browser menu option to verify each panel’s widgets operate in a mutually exclusive manner. CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES1236 8849CH32.qxd 10/16/07 12:51 PM Page 1236 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ■Source Code The ValidatorCtrls project is included under the Chapter 32 subdirectory. Working with Themes At this point, you have had the chance to work with numerous ASP.NET web controls. As you have seen, each control exposes a set of properties (many of which are inherited by System.Web.UI. WebControls.WebControl ) that allow you to establish a given UI look and feel (background color, font size, border style, and whatnot). Of course, on a multipaged website, it is quite common for the site as a whole to define a common look and feel for various types of widgets. For example, all TextBoxes might be configured to support a given font, all Buttons have a custom image, and all Calendars have a light blue border. Obviously it would be very labor intensive (and error prone) to establish the same property set- tings for every widget on every page within your website. Even if you were able to manually update the properties of each UI widget on each page, imagine how painful it would be when you now need to change the background color for each TextBox yet again. Clearly there must be a better way to apply sitewide UI settings. One approach that can be taken to simplify applying a common UI look and feel is to define style sheets. If you have a background in web development, you are aware that style sheets define a common set of UI-centric settings that are applied on the browser. As you would hope, ASP.NET web controls can be assigned a given style by assigning the CssStyle property. However, ASP.NET ships with an alternative technology to define a common UI termed themes. Unlike a style sheet, themes are applied on the web server (rather than the browser) and can be done so programmatically or declaratively. Given that a theme is applied on the web server, it has access to all the server-side resources on the website. Furthermore, themes are defined by author- ing the same markup you would find within any *.aspx file (as you may agree, the syntax of a style sheet is a bit on the terse side). Recall from Chapter 31 that ASP.NET web applications may define any number of “special” subdirectories, one of which is App_Theme. This single subdirectory may be further partitioned with additional subdirectories, each of which represents a possible theme on your site. For example, consider Figure 32-21, which illustrates a single App_Theme folder containing three subdirectories, each of which has a set of files that make up the theme itself. Figure 32-21. A single App_Theme folder may define numerous themes. CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES 1237 8849CH32.qxd 10/16/07 12:51 PM Page 1237 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Understanding *.skin Files The one file that every theme subdirectory is sure to have is a *.skin file. These files define the look and feel for various web controls. To illustrate, create a new website named FunWithThemes. Next, insert a new *.skin file (using the Web Site ➤ Add New Item menu option) named BasicGreen.skin, as shown in Figure 32-22. Figure 32-22. Inserting *.skin files Visual Studio 2008 will prompt you to confirm this file can be added into an App_Theme folder (which is exactly what we want). If you were now to look in your Solution Explorer, you would indeed find your App_Theme folder has a subfolder named BasicGreen containing your new BasicGreen.skin file. Recall that a *.skin file is where you are able to define the look and feel for various widgets using ASP.NET control declaration syntax. Sadly, the IDE does not provide designer support for *.skin files. One way to reduce the amount of typing time is to insert a temporary *.aspx file into your program ( temp.aspx, for example) that can be used to build up the UI of the widgets using the VS 2005 page designer. The resulting markup can then be copied and pasted into your *.skin file. When you do so, however, you must delete the ID attribute for each web control! This should make sense, given that we are not trying to define a UI look and feel for a particular Button (for example) but all Buttons. This being said, here is the markup for BasicGreen.skin, which defines a default look and feel for the Button, TextBox, and Calendar types: <asp:Button runat="server" BackColor="#80FF80"/> <asp:TextBox runat="server" BackColor="#80FF80"/> <asp:Calendar runat="server" BackColor="#80FF80"/> Notice that each widget still has the runat="server" attribute (which is mandatory), and none of the widgets have been assigned an ID attribute. CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES1238 8849CH32.qxd 10/16/07 12:51 PM Page 1238 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Now, let’s define a second theme named CrazyOrange. Using the Solution Explorer, right-click your App_Theme folder and add a new theme named CrazyOrange. This will create a new subdirec- tory under your site’s App_Theme folder. Next, right-click the new CrazyOrange folder within the Solution Explorer and select Add New Item. From the resulting dialog box, add a new *.skin file. Update the CrazyOrange.skin file to define a unique UI look and feel for the same web controls. For example: <asp:Button runat="server" BackColor="#FF8000"/> <asp:TextBox runat="server" BackColor="#FF8000"/> <asp:Calendar BackColor="White" BorderColor="Black" BorderStyle="Solid" CellSpacing="1" Font-Names="Verdana" Font-Size="9pt" ForeColor="Black" Height="250px" NextPrevFormat="ShortMonth" Width="330px" runat="server"> <SelectedDayStyle BackColor="#333399" ForeColor="White" /> <OtherMonthDayStyle ForeColor="#999999" /> <TodayDayStyle BackColor="#999999" ForeColor="White" /> <DayStyle BackColor="#CCCCCC" /> <NextPrevStyle Font-Bold="True" Font-Size="8pt" ForeColor="White" /> <DayHeaderStyle Font-Bold="True" Font-Size="8pt" ForeColor="#333333" Height="8pt" /> <TitleStyle BackColor="#333399" BorderStyle="Solid" Font-Bold="True" Font-Size="12pt" ForeColor="White" Height="12pt" /> </asp:Calendar> At this point, your Solution Explorer should like Figure 32-23. Figure 32-23. A single website with multiple themes So now that your site has a few themes defined, the next logical question is how to apply them to your pages? As you might guess, there are many ways to do so. ■Note To be sure, these example themes are quite bland. Feel free to spruce things up to your liking. Applying Sitewide Themes If you wish to make sure that every page in your site adheres to the same theme, the simplest way to do so is to update your web.config file. Open your current web.config file and locate the <pages> element within the scope of your <system.web> root element. If you add a theme attribute to the CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES 1239 8849CH32.qxd 10/16/07 12:51 PM Page 1239 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com <pages> element, this will ensure that every page in your website is assigned the selected theme (which is, of course, the name of one of the subdirectories under App_Theme). Here is the core update: <configuration> <system.web> <pages theme="BasicGreen"> </pages> </system.web> </configuration> If you were to now place various Buttons, Calendars, and TextBoxes onto your Default.aspx file and run the application, you would find each widget has the UI of BasicGreen. If you were to update the theme attribute to CrazyOrange and run the page again, you would find the UI defined by this theme is used instead. Applying Themes at the Page Level It is also possible to assign themes on a page-by-page level. This can be helpful in a variety of cir- cumstances. For example, perhaps your web.config file defines a sitewide theme (as described in the previous section); however, you wish to assign a different theme to a specific page. To do so, you can simply update the <%@Page%> directive. If you are using Visual Studio 2008 to do so, you will be happy to find that IntelliSense will display each defined theme within your App_Theme folder. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Theme ="CrazyOrange" %> Because we assigned the CrazyOrange theme to this page, but the Web.config file specified the BasicGreen theme, all pages but this page will be rendered using BasicGreen. The SkinID Property Sometimes you wish to define a set of possible UI look and feels for a single widget. For example, assume you want to define two possible UIs for the Button type within the CrazyOrange theme. When you wish do so, you may differentiate each look and feel using the SkinID property: <asp:Button runat="server" BackColor="#FF8000"/> <asp:Button runat="server" SkinID = "BigFontButton" Font-Size="30pt" BackColor="#FF8000"/> Now, if you have a page that makes use of the CrazyOrange theme, each Button will by default be assigned the unnamed Button skin. If you wish to have various buttons within the *.aspx file make use of the BigFontButton skin, simply specify the SkinID property within the markup: <asp:Button ID="Button2" runat="server" SkinID="BigFontButton" Text="Button" /><br /> As an example, Figure 32-24 shows a page that is making use of the CrazyOrange theme. The topmost Button is assigned the unnamed Button skin, while the Button on the bottom of the page has been assigned the SkinID of BigFontButton. CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES1240 8849CH32.qxd 10/16/07 12:51 PM Page 1240 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 32-24. Fun with SkinIDs Assigning Themes Programmatically Last but not least, it is possible to assign a theme in code. This can be helpful when you wish to provide a way for end users to select a theme for their current session. Of course, we have not yet examined how to build stateful web applications, so the current theme selection will be forgotten between postbacks. In a production-level site, you may wish to store the user’s current theme selec- tion within a session variable, or persist the theme selection to a database. Although we really have not examined the use of session variables at this point in the text, to illustrate how to assign a theme programmatically, update the UI of your Default.aspx file with three new Button types as shown in Figure 32-25. Once you have done so, handle the Click event for each Button type. Figure 32-25. The updated UI CHAPTER 32 ■ ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES 1241 8849CH32.qxd 10/16/07 12:51 PM Page 1241 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... from the browser that initiated the postback In the second browser instance, click the Refresh button (F5) You should not see the new item, given that the Page_Load event handler is reading directly from the cache (If you did see the value, the 15 seconds had already expired Either type faster or increase the amount of time the DataTable will remain in the cache.) Wait a few seconds and click the Refresh... out the role of the Application_Error() event handler Recall that a specific page may handle the Error event to process any unhandled exception that occurred within the scope of the page itself In a similar light, the Application_Error() event handler is the final place to handle an exception that was not handled by a given page As with the page-level Error event, you are able to access the specific System.Exception... http://www.simpopdf.com CHAPTER 33 s ASP.NET STATE MANAGEMENT TECHNIQUES persist user data in a permanent manner, ASP.NET provides an out-of -the- box Profile API We’ll examine the details of each approach in turn, beginning with the topic of ASP.NET view state Understanding the Role of ASP.NET View State fr ee -e bo o ks - do w nl oa d o rg The term view state has been thrown out a few times here and in the previous two chapters... state management Here you will learn the role of view state, session and application variables (including the application cache), cookie data, and the ASP.NET Profile API The Issue of State w fr At the beginning of the Chapter 31, I pointed out that HTTP on the Web results in a stateless wire protocol This very fact makes web development extremely different from the process of building an executable assembly... between the browser and a specific page The data assigned to this field is a Base64-encoded string that contains a set of name/value pairs that represent the values of each GUI widget on the page at hand The System.Web.UI.Page base class’s Init event handler is the entity in charge of reading the incoming values found within the VIEWSTATE field to populate the appropriate member variables in the derived... visible is the fact that the *.aspx file has explicitly defined the ListBox items within the scope of the HTML tags Thus, the ListBox items will be autogenerated each time the web server responds to the client However, assume that your ListBox is dynamically populated within the code-behind file rather than within the HTML definition First, remove the declarations from the current... nl ASP.NET pages reserve a small part of the VIEWSTATE string for internal use Given this, you will find that the VIEWSTATE field will still appear in the client-side source even when the entire page (and all the controls) have disabled view state ee -e bo o In addition to the EnableViewState property, the System.Web.UI.Control base class provides an inherited property named ViewState Under the hood,... be used to identify the user and pull details from a database The System.Web.HttpCookie type is the class that represents the server side of the cookie data (persistent or temporary) When you wish to create a new cookie, you access the Response.Cookies property Once the new HttpCookie is inserted into the internal collection, the name/value pairs flow back to the browser within the HTTP header To check... named UserTheme, which is formally assigned within the Page_PreInit() event handler Also note that when the user clicks a given Button, we programmatically force the PreInit event to fire by calling Server.Transfer() and requesting the current page once again If you were to run this page, you would now find that you can establish your theme via various Button clicks s Source Code The FunWithThemes project... http://www.simpopdf.com CHAPTER 33 s ASP.NET STATE MANAGEMENT TECHNIQUES rg Next, construct the web UI as shown in Figure 33-1 oa d o Figure 33-1 The UI for the simple state page nl The server-side Click event handler for the Set button (named btnSetCar) will allow the user to assign the string member variable to the value within the TextBox (named txtFavCar): ks - do w protected void btnSetCar_Click(object . understand the role of the Global.asax file. ■Source Code The ViewStateApp project is included under the Chapter 33 subdirectory. CHAPTER 33 ■ ASP .NET STATE MANAGEMENT TECHNIQUES1 250 8849CH 33. qxd 10/ 17/07. Figure 32 -20 shows one possible UI. CHAPTER 32 ■ ASP .NET WEB CONTROLS, THEMES, AND MASTER PAGES 1 2 35 8849CH32.qxd 10/ 16/07 12 :51 PM Page 1 2 35 www.free-ebooks-download.org Simpo PDF Merge and Split. containing a set of event handlers: CHAPTER 33 ■ ASP .NET STATE MANAGEMENT TECHNIQUES 1 251 8849CH 33. qxd 10/ 17/07 5: 53 PM Page 1 251 www.free-ebooks-download.org Simpo PDF Merge and Split Unregistered

Ngày đăng: 12/08/2014, 23:20

Từ khóa liên quan

Mục lục

  • Prelims

  • Chapter 1

  • Chapter 2

  • Chapter 3

  • Chapter 4

  • Chapter 5

  • Chapter 6

  • Chapter 7

  • Chapter 8

  • Chapter 9

  • Chapter 10

  • Chapter 11

  • Chapter 12

  • Chapter 13

  • Chapter 14

  • Chapter 15

  • Chapter 16

  • Chapter 17

  • Chapter 18

  • Chapter 19

Tài liệu cùng người dùng

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

Tài liệu liên quan