ASP.NET 2.0 - PART 1 pdf

94 177 0
ASP.NET 2.0 - PART 1 pdf

Đ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

ASP.NET 2.0 ALL-IN-ONE DESK REFERENCE FOR DUMmIES ‰ by Doug Lowe, Jeff Cogswell, and Ken Cox, Microsoft MVP ASP.NET 2.0 ALL-IN-ONE DESK REFERENCE FOR DUMmIES ‰ by Doug Lowe, Jeff Cogswell, and Ken Cox, Microsoft MVP ASP.NET 2.0 All-in-One Desk Reference For Dummies® Published by Wiley Publishing, Inc 111 River Street Hoboken, NJ 07030-5774 www.wiley.com Copyright © 2006 by Wiley Publishing, Inc., Indianapolis, Indiana Published by Wiley Publishing, Inc., Indianapolis, Indiana Published simultaneously in Canada No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600 Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permissions Trademarks: Wiley, the Wiley Publishing logo, For Dummies, the Dummies Man logo, A Reference for the Rest of Us!, The Dummies Way, Dummies Daily, The Fun and Easy Way, Dummies.com, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc and/or its affiliates in the United States and other countries, and may not be used without written permission All other trademarks are the property of their respective owners Wiley Publishing, Inc., is not associated with any product or vendor mentioned in this book LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ For general information on our other products and services, please contact our Customer Care Department within the U.S at 800-762-2974, outside the U.S at 317-572-3993, or fax 317-572-4002 For technical support, please visit www.wiley.com/techsupport Wiley also publishes its books in a variety of electronic formats Some content that appears in print may not be available in electronic books Library of Congress Control Number: 2006922516 ISBN-13: 978-0-471-78598-9 ISBN-10: 0-471-78598-9 Manufactured in the United States of America 10 1B/SQ/QW/QW/IN About the Author Doug Lowe has written a bevy of computer books, including more than 35 For Dummies books Among his most recent are ASP.NET Everyday Applications For Dummies, Java All-In-One Desk Reference For Dummies, Networking For Dummies, 7th Edition, Networking For Dummies All-In-One Desk Reference, Second Edition, PowerPoint 2003 For Dummies, and Word 2003 All-In-One Desk Reference For Dummies He lives in sunny Fresno, California, where the weather is always bad for half of the farmers, with his wife, the youngest of three daughters, and a couple of crazy dogs He is the Information Technology Director for Blair, Church & Flynn Consulting Engineers, an engineering firm in nearby Clovis, CA Jeff Cogswell is a software engineer and trainer living in the Cincinnati area He has written several books, including two previous Dummies books, one on C++ and one on LAMP When not programming or writing about computers, he enjoys traveling and writing fiction and screenplays Jeff also conducts ASP.NET training sessions; contact him at training@jcogs.com or visit www.jcogs.com for more information Ken Cox is a Canadian writer and programmer whose claim to fame is that he has chatted in English and French with Queen Elizabeth II of England His degree in Radio and Television Arts from Ryerson University led to a 25-year career as a broadcast journalist in Toronto and Quebec City Waving his college certificate in Technical Communication, he launched a second career as a technical writer for companies including Nortel (yes, before it wilted) Somehow, he parlayed zero/zilch formal training in computers into a third career as a programming writer, technical editor, and Web developer Microsoft has repeatedly honoured him as a Most Valuable Professional (MVP) for ASP.NET in recognition of his contributions to the NET developer community Ken, his wife Vilia, and their dog Goldie (a GoldenDoodle) spend spring, summer, and fall at a peaceful lakefront home in a forest in Nipissing Township, Ontario They winter in Victoria, British Columbia Dedication To Debbie, who wondered where I was — Doug Lowe To my wife, Vilia, for encouraging me to pursue my dreams — Ken Cox Author’s Acknowledgments I’d like to thank everyone who helped make this book happen, starting with project editor Blair Pottenger, who did a great job guiding this project through from start to finish I’d also like to thank my co-authors Ken Cox and Jeff Cogswell, and copy editor Barry Childs-Helton who dotted my t’s and crossed my eyes, or something like that, and managed to turn my strange ramblings into readable English And, as always, thanks to all the behind-thescenes people who chipped in with help whenever help was needed — Doug Lowe Thanks to Scott Guthrie, Nikhil Kothari, Rich Ersek and the the rest of Microsoft’s Web Platform & Tools team for creating the fascinating ASP.NET technologies.Thanks also to Katie Feltman, Blair Pottenger, and Doug Lowe for giving me the opportunity to contribute to this book — Ken Cox Publisher’s Acknowledgments We’re proud of this book; please send us your comments through our online registration form located at www.dummies.com/register/ Some of the people who helped bring this book to market include the following: Acquisitions, Editorial, and Media Development Composition Services Project Editor: Blair J Pottenger Acquisitions Editor: Katie Feltman Copy Editor: Barry Childs-Helton Technical Editor: Ken Cox Editorial Manager: Kevin Kirschner Media Development Specialists: Angela Denny, Kate Jenkins, Steven Kudirka, Kit Malone, Travis Silvers Project Coordinator: Jennifer Theriot Layout and Graphics: Claudia Bell, Carl Byers, Andrea Dahl, Denny Hager, Joyce Haughey, Stephanie D Jumper, Barry Offringa, Melanee Prendergast, Julia Trippetti Proofreaders: John Greenough, Leeann Harney, Christy Pingleton, Linda Quigley Indexer: Kevin Broccoli Media Development Coordinator: Laura Atkinson Media Project Supervisor: Laura Moss Media Development Manager: Laura VanWinkle Media Development Associate Producer: Richard Graves Editorial Assistant: Amanda Foxworth Sr Editorial Assistant: Cherie Case Cartoons: Rich Tennant (www.the5thwave.com) Publishing and Editorial for Technology Dummies Richard Swadley, Vice President and Executive Group Publisher Andy Cummings, Vice President and Publisher Mary Bednarek, Executive Acquisitions Director Mary C Corder, Editorial Director Publishing for Consumer Dummies Diane Graves Steele, Vice President and Publisher Joyce Pepple, Acquisitions Director Composition Services Gerry Fahey, Vice President of Production Services Debbie Stailey, Director of Composition Services Table of Contents Introduction About This Book .2 How to Use This Book .3 How This Book Is Organized Book I: ASP.NET Basics Book II: Web Controls Book III: HTML Book IV: C# Book V: Visual Basic .4 Book VI: Database Programming Book VII: Using the NET Framework Book VIII: Advanced ASP.NET Programming .4 Icons Used in This Book Where to Go from Here Book I: ASP.NET Basics Chapter 1: Welcome to ASP.NET Programming What Is ASP.NET, and Why Is It So Great? .9 Windows and IIS dependence .10 Object orientation 11 Choice of languages .11 Visual Studio 12 Understanding Web Servers and Browsers 12 Understanding Static Web Pages 13 Understanding Dynamic Web Pages 14 Looking at a Simple ASP.NET Application 15 The aspx (Markup) File for the Simple Calculator Application 17 The Code-Behind File of the Simple Calculator Application 18 Chapter 2: Installing Visual Studio Web Developer 2005 Express Edition or Visual Studio 2005 21 Looking at Visual Studio 2005 Editions .21 Considering Visual Web Developer 2005 Express Edition 22 Installing Visual Web Developer 2005 Express Edition .22 Registering Visual Web Developer 2005 Express Edition 27 Installing Visual Studio 2005 30 Chapter 4: Understanding Postback, Events, and Code-Behind In This Chapter ߜ Posting pages to the server ߜ Working with events in Visual Basic ߜ Working with events in C# ߜ Getting behind the scenes of code-behind T hree of the most important concepts in ASP.NET programming are the ideas of (1) posting pages to the server, (2) handling events, and (3) code-behind Postback refers to what happens when the user clicks a button or performs some other action that sends the page displayed in the browser window to the server so whatever data the user entered on the page can be processed Events are the processes that ASP.NET uses to deal with user interaction when a page has been posted And code-behind is how ASP.NET lets you separate the code that’s executed when events occur from the markup code that defines how pages appear This chapter introduces you to these three all-important ASP.NET concepts All code listings used in this book are available for download at www.dummies com/go/aspnetaiofd Understanding Postback You’re probably familiar with Web pages that include a Submit button For example, consider a typical search-engine Web page that has a text box and a Submit button When you click the Submit button, the text you entered into the text box is sent to the search-engine’s server, which looks up the results of your search and sends the results back to the browser The process of sending the page to the server is called a postback Note that the term postback implies that the ASP.NET page has already been displayed in the browser When the user clicks a button, the page along with any data entered by the user is sent to the server The server then runs the code associated with the page to process the data entered by the user 54 Using the IsPostBack Variable When a page is posted, ASP.NET gets busy with the following tasks: ASP.NET receives the data sent back to the server, including any data that the user entered into controls such as text boxes ASP.NET determines which page in the application was displayed in the browser window and loads that page into memory on the server The properties of any controls that appear on that page are set based on the data entered by the user For example, if the page contains a text box and the user entered data into that text box, the Text property of the text box is set to the data value entered by the user A special variable named IsPostBack is set to True This enables the application to determine if a postback is occurring (The next section digs into how to make this process happen, and explains why it’s significant.) The code that handles events generated for the page is executed (For more about what that means, flip ahead to the later parts of this chapter, and look for the section “Understanding Events.”) After all of the event code has been executed, the page is sent back to the browser in the form of HTML so the user can see whatever updates have been applied to the page One important thing to know about the way ASP.NET applications work is to realize that not every type of control causes the page to be posted back to the server For example, when a user selects an item from a drop-down list, the page isn’t normally posted Nor is the page posted when the user selects a check box or radio button or enters a value into a text box The user has to click a button to post the page (As described in Book 2, you can change the behavior of controls such as drop-down lists and check boxes so they post back when the user selects them — but don’t post the page by default.) Using the IsPostBack Variable A postback occurs only when the user clicks a button or performs some other action that causes the page currently displayed by the browser to be sent back to the server The first time a page is retrieved by a user, a postback doesn’t occur For instance, when the user starts the Simple Calculator application (our example from the previous chapter of this mini-book) by browsing to the application’s Default.aspx page, the page is loaded into server memory and events are processed, but a postback doesn’t occur (In the case of the Simple Calculator application, a postback doesn’t occur until the user clicks the Add button.) As you’ll see throughout this book, you’ll often write code that checks to see if a postback has occurred For example, suppose you want to initialize the Understanding Events 55 If IsPostBack Then lblGreeting.Text = “Hello Again!” Else lblGreeting.Text = “Good Morning!” End If If you’re working in C#, the code would look more like this: if (IsPostBack) lblGreeting.Text = “Hello Again!”; else lblGreeting.Text = “Good Morning!”; Either way, the IsPostBack variable is used to determine whether a postback has occurred — if it has, the label’s Text property is set accordingly Careful how you use this one Using IsPostBack incorrectly can lead to all sorts of programming problems If you find that a variable or field is incorrectly reset to the same value each time the page is posted, you may need to add an if statement to set the variable or field only when IsPostBack is false You’ll see many more examples of the IsPostBack variable in use throughout this book Understanding Events Events are the key to ASP.NET programming because most of the code you write for an ASP.NET application is executed in response to events that are raised as a page is processed In essence, an ASP.NET application consists of two things: ✦ A set of Web pages that contain controls that users can interact with When a user interacts with one or more of the controls on a page, an event is generated to record the interaction ✦ Code executed in response to the events generated when the user interacts with the controls on the Web pages For example, consider the Simple Calculator application presented in the previous chapter of this mini-book In practical terms, it’s a Web page that Book I Chapter Understanding Postback, Events, and Code-Behind Text property of a label to “Good Morning!” the first time a page is posted, but to change the label whenever the user posts back to the page by clicking a button; then the label should display “Hello Again!” instead of “Good Morning!” In that case, you might write Visual Basic code that looks like the following: 56 Using the Handles Clause in Visual Basic displays some labels, text boxes, a button, and some code that’s executed when the user clicks the button Button-click events are among the most common types of events — but by no means the only events — that ASP.NET pages encounter Every time a page is posted to a Web server, a series of events are processed — or raised — by the ASP.NET server In particular, the following events are always raised every time a page is posted: ✦ Preinit: This is the first event raised as a part of page initialization It occurs before ASP.NET initializes the page It allows you to change properties that may affect the way the page is initialized ✦ Init: This event occurs after ASP.NET has initialized the page; it allows you to add additional initialization code ✦ Load: This event kicks in after the controls have been initialized with their correct values ✦ Control events: Any events that result from the user interacting with controls, such as when the user clicks a button or selects an item from a drop-down list, are raised after the Load event For example, if the user clicks a button, the Click event will be raised after the Load event Note that it’s entirely possible (and quite common) for more than one control event to occur each time a page is posted For example, if a user selects an item from a drop-down list, clicks a check box to select it, then clicks a button, the page is posted when the button is clicked Then three events are raised after the Load event: one to indicate that the user has selected an item from the drop-down list, a second to indicate that the user has clicked the check box, and a third to indicate that the user has clicked the button ✦ PreRender: This event is raised after all of the control events have been raised but before the HTML that will be sent back to the browser is generated ✦ Unload: This event is raised when the page has been sent back to the browser The process of connecting a method (or, as it’s called in VB.NET, a Sub procedure) to an event is called wiring There are two ways to wire events, depending on whether you’re working in Visual Basic or C# The next two sections describe the two techniques (Hint: No screwdriver required.) Using the Handles Clause in Visual Basic The Handles clause is it a piece of classical Christmas music (say, what Handel wrote right after he finished Messiah)? Nope It actually refers to a clause you can add to a Sub procedure in Visual Basic Its job is to designate Using the Handles Clause in Visual Basic 57 The format of the Sub statement with a Handles clause is as follows: Protected Sub name(parameters) Handles control.event End Sub For example, here’s a Sub procedure that handles a button-click event: Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click Button1.Text = “Got me!” End Sub Here, the Text property of the button named Button1 is changed to “Got me!” when the button is clicked The Sub procedure has two parameters, named sender and e The sender parameter refers to the control that generated the event, in this case, Button1 The e parameter provides additional arguments that might be useful to the event handler (For more information on event handler arguments, you can look up System.EventArgs in the Visual Studio help.) Fortunately, you don’t have to worry about coding the Handles clause — or the parameters — if you don’t want to Instead, you can simply double-click a form control in the Web Designer view Then Visual Studio automatically creates an event handler with the proper Handles clause and parameters Note that it’s possible for a single Sub procedure to handle an event for two or more controls Here’s an interesting, if not very practical, example: Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click, Button2.Click If sender Is Button1 Then Button1.Text = “” Button2.Text = “Click me!” Else Button1.Text = “Click me!” Button2.Text = “” End If End Sub In this example, the text “Click me!” jumps from button to button when the user clicks either Button1 or Button2 Book I Chapter Understanding Postback, Events, and Code-Behind that the procedure should be invoked when a particular event is raised In short, the Handles clause is what links controls in an aspx file to procedures in a Visual Basic code-behind file (The Handles clause only applies to VB.NET programs For a look at how events are handled in C#, refer to the next section.) 58 Designating an Event Handler in C# Designating an Event Handler in C# C# doesn’t have an equivalent to Visual Basic’s Handles clause Instead, C# programs take a different approach to designating the code that is executed in response to events Instead of specifying the event handling in the codebehind file, you specify it in the aspx file by adding an OnEvent attribute to the tag for the control For example, here’s the code for a button that specifies an event handler: Here the OnClick attribute indicates that the method named btnAdd_Click should be executed when the user clicks the button In the code-behind file, the btnAdd_Click method makes no reference to the btnAdd control or the Click event Like Visual Basic event handlers, however, C# event handlers must specify the sender and e parameters Here’s an example: protected void btnAdd_Click(object sender, EventArgs e) { } Once again, you don’t have to worry about coding these parameters or the OnEvent attributes yourself Simply double-click a control in the Web Designer and Visual Studio will automatically create an event handler for you with the correct OnEvent attribute and the correct parameters Note that Visual Basic also lets you use the OnEvent technique to handle events However, the Handles clause is more common in VB.NET because Visual Studio uses it for generated code Using C#’s Auto Event Wireup In addition to the OnEvent technique described in the previous section, C# uses a technique called auto event wireup to automatically call the methods that handle page-level events such as Init and Load Then all you have to to handle these events is create a method with the appropriate name in the code-behind file The following methods are automatically wired: ✦ Page_Init: Wired to the Init method for the page This method executes after the page is initialized ✦ Page_Load: This method executes when the page is loaded Understanding Code-Behind 59 ✦ Page_PreRender: This method executes after all control events for the page have been executed, but before any HTML has been generated for the page Book I Chapter ✦ Page_Unload: This event is typically where you put any cleanup tasks required by the application, such as closing files or terminating database connections Understanding Postback, Events, and Code-Behind Auto-event wireup is controlled (no surprise) by the AutoEventWireup attribute on the Page directive that appears at the top of every aspx file For example: When you use Visual Basic, AutoEventWireup is set to False Then the methods that handle page-level events must specify a Handles clause, as in this example: Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load End Sub Understanding Code-Behind Code-behind is one of the most important concepts (and techniques) in ASP.NET programming It uses a separate file to contain the VB.NET or C# code that’s executed in response to events — and only that code — rather than intermingling the VB.NET or C# code with the aspx code that defines the Web page The main benefit of code-behind is to separate the code that defines the appearance of a Web page from the code that defines the behavior of the page Result: code that is easier to write, debug, and maintain And it lets you direct your focus while you’re developing your applications You can begin by creating a basic page that has the controls you need, without worrying too much about how the page looks Then you can focus on getting the code to work so the page does its job correctly After you have the code working, you can return to the aspx file to refine the appearance of the page In the real world, there isn’t always a clean separation between the appearance of a page and its behavior Often, as a result, you end up alternating between tweaking the aspx file and tinkering with the code-behind file; changes in one file inevitably affect code in the other file Even so, separating the appearancemaking code from the behavioral code is a big step forward 60 Using Single-File Pages To understand how code-behind works, you need to understand two things: partial classes and code generation ✦ A partial class is a VB.NET or C# class defined by two or more files Partial classes are integral to code-behind because a Web page must be defined by a single class that represents the controls on the page (that is, the appearance of the page) as well as the event handlers for the page (that is, the behavior of the page) The code-behind file is a partial class that supplies the methods that handle events The other part of the class is what the aspx file provides ✦ Code generation (that is, the automatic creation of code) is a required step because the aspx file is not written in either C# or Visual Basic Instead, it consists of a mixture of HTML and ASP.NET markup tags When ASP.NET processes a page, it reads this markup and then generates C# or VB.NET code — which represents the page, its HTML, and all its controls This code is a partial class that matches the partial class represented by the code-behind file Thus the complete processing for an ASP.NET page consists of the following events: The aspx file is processed by ASP.NET, which generates a source file that defines a partial class that represents the HTML and controls for the page This source file is generated in C# or VB.NET, depending on the language specified for the page The source file generated in Step is compiled by the C# or VB.NET compiler to create a partial class The code-behind file is compiled by the C# or VB.NET compiler to create a partial class The partial classes created in Steps and are combined to create the complete class that represents the page The resulting class is loaded into memory and executed Using Single-File Pages Code-behind isn’t the only code model supported by ASP.NET If you prefer, you can also mix code directly in the aspx file, eliminating the need for a code-behind file To so, you simply uncheck the “Place code in separate file” option when you create a new Web page Then, Visual Studio inserts special tags that contain the code that would otherwise be placed in the code-behind file Using Single-File Pages 61 Listing 4-1: The Simple Calculator application using the single-page model (C#) protected void btnAdd_Click(object sender, EventArgs e) { decimal num1 = Decimal.Parse(txtNumber1.Text); decimal num2 = Decimal.Parse(txtNumber2.Text); decimal ans = num1 + num2; txtAnswer.Text = ans.ToString(); } Untitled Page Book I Chapter Understanding Postback, Events, and Code-Behind Note that the Web Designer works pretty much the same whether you use code-behind or the single-file model Either way, you can double-click a control to call up the Code Editor to write event-handler code However, the resulting aspx file looks very different if you use the single-file model For example, Listing 4-1 shows the complete aspx file for the Simple Calculator application implemented as a single page As you can see, the btnAdd_Click method is contained within a element rather than in a separate file 62 Book I: ASP.NET Basics Chapter 5: Creating Multipage Applications In This Chapter ߜ Learning the basics of a multipage application ߜ Adding pages to a Web project ߜ Getting from one page to another ߜ Keeping track of an application’s state ߜ Dipping your toe into data binding ߜ Using Master Pages to create a consistent look among your pages O nly the most trivial and boring of Web sites have just one page Most Web sites go way beyond one page — perhaps to dozens or even hundreds of pages Pervasive as they are, these multipage Web sites present several interesting challenges This chapter shows how to add pages to your Web applications — and deal with the complications that result from having multiple pages Those include such issues as how your users can get from one page to another, how to create pages that have a consistent appearance, and how to manage the “state” of an application so the application knows where it’s been and where it’s going All code listings used in this book are available for download at www dummies.com/go/aspnetaiofd Understanding the Basics of a Multipage Application To illustrate the programming techniques you’ll learn in this chapter, we’ll take a close look at a simple shopping cart application, similar to many similar applications you’ve undoubtedly encountered on the Web Of course, this application is dramatically simplified so we can focus on a few basic programming techniques For example, this online store (which sells Halloween costumes) has only a few products for sale And the shopping cart doesn’t mention the price of the products you buy — just the description and quantity of each product (Hey, why not? Imaginary stores can afford to be simplistic.) 64 Understanding the Basics of a Multipage Application Figure 5-1 shows the first page of the Shopping Cart application, Default aspx Here you can see that the page consists of three controls: a list box from which you can select a product, a text box in which you can enter a quantity, and a button you can click to add the selected product to your shopping cart Figure 5-1: The first page of the Shopping Cart application When the user selects a product, enters a quantity, and clicks the button, the application adds the selected product to the user’s shopping cart Then the application displays the second page of the application — Cart.aspx — as shown in Figure 5-2, where a list box displays the contents of the user’s shopping cart Figure 5-2: The second page of the Shopping Cart application Understanding the Basics of a Multipage Application 65 Although this application is simple, it utilizes some important ASP.NET programming techniques — in particular, these: ✦ The application uses two pages, so it must provide a way for one page to lead to the other For example, when the user clicks the Add To Cart button on the Default.aspx page, the application displays the Cart aspx page And when the user clicks the Continue Shopping button on the Cart.aspx page, the application displays the Default.aspx page (For more about adding pages to your Web site and navigating between them, see the “Adding Pages” section later in this chapter.) ✦ In addition to the classes that represent the Default.aspx and Cart.aspx pages, the application uses a custom class called ShoppingCartItem to represent the items in the shopping cart (Books and get into the fine details of classes) ✦ The application uses an ASP.NET programming feature called session state to store the actual shopping cart data A NET Framework class called ArrayList — which is designed to store collections of repeating data — stores the data and keeps track of the session state (For more about how that works, see the “Using Session State” section later in this chapter.) ✦ The application uses another ASP.NET programming feature called data binding for automatic display of the data stored in the shopping cart’s ArrayList object The data shows up on-screen in the list box that appears in the Cart.aspx page (This chapter gives you a glimpse of data binding, but the best in-depth look is in Book 6.) ✦ Notice how both pages in this application have the same graphic displayed at the top? You could simply copy and paste this graphic on each page But there’s a better way: Master Pages The Master Page feature makes it easy to create applications whose pages have common elements such as banners, navigation menus, and so on (For the masterful details, see the “Using Master Pages” section later in this chapter.) The rest of this chapter takes a closer look at each of these programming techniques Then I present the code for the Shopping Cart application so you can see how everything works together Book I Chapter Creating Multipage Applications The second page of the Shopping Cart application has two buttons The first simply returns to the first page so the user can change what’s in the shopping cart by adding or removing items The second button is a Check Out button that okay doesn’t anything in this particular application It’s there only because in a realistic Shopping Cart application, you’d see a button that lets the user complete the order 66 Adding Pages Adding Pages When you first create an ASP.NET Web application, the application consists of a single Web page named Default.aspx Few applications use just a single page, so one of the first things you have to get Visual Studio to is add a new page to your Web site Fortunately, the procedure is relatively simple Just follow these steps: Choose Website➪Add New Item If you prefer, you can use one of the following shortcuts: • Ctrl+Shift+A • The Add New Item button in the Standard toolbar (shown in the margin) • Right-click the project in the Solution Explorer, then choose Add New Item Either way, the Add New Item dialog box appears, as shown in Figure 5-3 Figure 5-3: The Add New Item dialog box Make sure Web Form is selected in the Templates box Usually this item is already selected But check to make sure Enter a name for the page in the Name text box The default name is — ahem — Defaultx.aspx Now, I’m guessing you don’t want to create a Web site full of pages named Default1.aspx, Default2.aspx, and so on So give your page a more meaningful name Select the programming language Redirecting to Another Page 67 The default is the language you chose when you created the Web site Sure, you can mix languages within a single Web site, but it’s seldom a good idea to so Normally it’s best to leave this option untouched This option, which is checked by default, creates a code-behind file for the page’s event handlers If you don’t want to use a code-behind file, uncheck this option If you’re using Master Pages, check the Select Master Page option For more about how Master Pages work, see the “Using Master Pages” section later in this chapter Click Add Visual Studio grinds and whirs for a moment, and then adds the page You’ll see an icon for the new page in the Solution Explorer, and the aspx file opens in the Web Designer window (If you selected C# as your language, the page opens in Source view; if you selected Visual Basic, the page opens in Design view.) You can, of course, add as many pages as you want to an ASP.NET project If a project requires a lot of pages, you may want to use subfolders to organize the pages To create a subfolder, right-click the project in the Solution Explorer and choose New Folder Then type a name for the new folder and press Enter Redirecting to Another Page When your Web site has more than one page in it, you need a way to take the user from one page to another ASP.NET provides several ways to this The most common is to call Response.Redirect in the Click event handler for a button For example, if you want the page Default.aspx to be displayed when the user clicks a button named btnContinue, you would code the following C# event handler for the btnContinue button: protected void btnContinue_Click(object sender, EventArgs e) { Response.Redirect(“Default.aspx”); } The VB.NET version of this event handler would look like this: Protected Sub btnContinue_Click( _ ByVal sender As Object, _ Creating Multipage Applications Make sure the Place Code in Separate File option is checked Book I Chapter ... books Library of Congress Control Number: 2006922 516 ISBN -1 3 : 97 8-0 -4 7 1- 7 859 8-9 ISBN -1 0 : 0-4 7 1- 7 859 8-9 Manufactured in the United States of America 10 1B/SQ/QW/QW/IN About the Author Doug Lowe has... simplifies the job of creating ASP.NET Web applications Figure 1- 1 shows an ASP.NET Web application being developed in Visual Studio, using a what-you-see-is-what-you-get Web-page editor This approach... 11 5 Validating the Hard Way 11 5 Validation Controls to the Rescue! 11 7 Using the RequiredFieldValidator Control 11 8 Using the CompareValidator Control .12 0 Using

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

Từ khóa liên quan

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

Tài liệu liên quan