Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 2 potx

90 286 0
Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 2 potx

Đ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

HTTP is known as a stateless protocol. This is because it doesn't know whether the request that has been made is part of an ongoing correspondence or just a single message (just the same way your postman won't know whether a letter is the first from your friend or the fifteenth). HTTP is stateless because it was only intended for the simple task of retrieving pages for display. The Internet would be very slow and might even collapse if permanent connections (states) needed to be maintained between clients and servers, as people moved from one page to another. Statelessness makes the Internet faster, but the downside is that HTTP by itself can't distinguish between different users. A Web server based on pure HTML will treat all requests with the same status, that of an unknown user. Obviously, the modern needs of the Internet require that you can identify users and track their moves through the various pages needed for accomplishing a task on a Web site. As seen later in the book, ASP.NET creates a state that can be used by programmers. Where ASP.NET Fits in with the .NET Framework ASP.NET adds a step to the request-response mechanism; after the server receives the request, it reads the page from the hard drive. But rather then containing just text and HTML tags, an ASP.NET page also contains script that is interpreted to build features into the page. Figure 3-2 The process is illustrated in Figure 3-2 and can be explained as follows: 1. The client requests a Web page by typing an URL into the browser and clicking GO. 2. Web server locates on its hard drive the page that was requested. 63 Server Controls and Variables 3. If the name of the Web page has an .aspx extension, the server processes the page – it runs the script code. If the ASP.NET code hasn't been compiled before, it is compiled now. The code is executed to create a pure HTML stream. 4. The HTML stream is returned to the client. 5. The client browser interprets (converts) the HTML code and text into a displayed Web page. The addition of ASP.NET implies that the HTML is created dynamically. This has many advantages: you can return information to the user based on their responses in a form, customize Web pages for a particular browser; or even personalize information for each user. All of this is possible because the code you write is converted into an HTML page when it is requested. Now that you have a basic understanding of how ASP.NET pages compare to plain HTML pages, it's time to start studying forms. Mastery of the concepts of forms allows us to obtain information from users. The subsequent chapters will discuss manipulation of this information and saving it to databases. The <form> Tag in ASP.NET ASP.NET has a set of form controls that are similar to HTML form controls. The main difference is that ASP.NET controls are actually constructed dynamically on the server at the time of request, and then sent out. The ASP.NET version requires only a few characters of coding: <form ID="MyForm" runat="server"> ASP.NET form </form> It takes only one attribute (runat="server") to tell the Web server that it should process the form itself, rather than just sending it out to the browser. If you have worked with HTML forms you may wonder about which METHOD is used. All ASP.NET forms are sent by the POST method. The <form> tag allows you to process form controls (such as checkboxes and dropdown lists) on the server. ASP.NET introduces its own customized versions of these controls. There are several advantages to using the ASP.NET form controls: ❑ .NET automatically creates and handles a sense of state for us. This allows us to know if the person requesting the form is the same person that requested another page. ❑ ASP.NET offers some very sophisticated controls including calendars and grids for the display of data. ❑ The content of the controls can be generated from databases or business logic. ❑ The information entered by users into controls can be validated to avoid data entry mistakes. Using ASP.NET Server Controls This section demonstrates how some of the ASP.NET server controls work and compares the way in which they are used to the way in which information is passed in their equivalent HTML form control. It 64 Chapter 3 also shows the separation of the presentation code (HTML) from the code that provides the content (ASP.NET). All Web controls have two required attributes. The first is runat="server", which instructs ASP.NET to handle the control at the server and thus, implement all of the ASP.NET features for the control including the creation of state. The second is the id="MyControlName", which manipulates the control in code. Before going into the details, let's take a look at the most commonly used ASP.NET server controls. We've included a comparison to the HTML form tags that you have used in the past. <asp:Label> Let's start with a small but very useful control, the <asp:Label> control. This control provides an effective way of displaying text on your Web page in ASP.NET, similar to the HTML <span> tag. By having a control for text, you can manipulate its contents and visibility from your ASP.NET code. <asp:Label> Attributes The <asp:Label> control is just like any normal HTML form control, in that, it has a collection of attributes you can set; the runat="server" and id attributes are used in every ASP.NET control. Other attributes are optional including: ASP.NET Web Control Similar HTML Form Tag Purpose <asp:Label> <Span>, <Div>, simple text Display text <asp:ListBox> <Select> Offer the user a list of items from which to select. <asp:DropDownList> <Select> Offer the user a list of items from which to select in a compact format <asp:TextBox> <Input Type="Text"> Accept typed input from user <asp:RadioButton> and <asp:RadioButtonList> <Input Type="Radio"> Allow user to make one selection from a list of options. <asp:CheckBox> and <asp:CheckBoxList> <Input Type="CheckBox"> Allow user to turn a feature on or off <asp:Button> <Input Type="submit"> Send the user's input to the server ASP.NET server controls are also called Web Controls, a term that we'll be regularly using throughout this book. 65 Server Controls and Variables ❑ Text: Sets the text that you want the label to display ❑ Visible: Sets the visibility of the label on the page (true or false) ❑ BackColor: Sets the background color of the label ❑ ForeColor: Sets the foreground color of the label ❑ Height: Sets the height in pixels of the label ❑ Width: Sets the width of the label You can use the class browser mentioned in Chapter 2 to see all the properties of any control. <asp:Label> Examples The basic syntax of <asp:Label> is simple: <asp:Label id="lblMyLabel" runat="server">Sale Ends May 2nd</asp:Label> The <asp:> prefix indicates that this control is part of the set of built-in ASP.NET controls. It is possible to create custom controls that have prefixes of the developer's choice. We will look at this in Chapter 13. In the context of a Web page, the <asp:Label> control looks like the following (refer to the file Ch03 \Demo-Label01.aspx in the code download): <html> <head> <title>ASP.NET Controls Demo</title> </head> <body> Demo of the asp:Label control<br /> <form id="frmDemo" runat="server"> <asp:Label id="lblGreeting1" runat="server">Text of asp:Label</asp:Label> </form> </body> </html> The id attribute is used to uniquely identify this control so that you can refer to it in your ASP.NET code. The runat="server" attribute tells the server to process the control and generate HTML code to be sent to the client. The text between the opening and closing labels provides the characters to show up in the label. Alternatively, you can specify the text in an attribute. This way, everything can be contained within the opening tag, in which case, you need to close the tag in the following way: <asp:Label id="lblGreeting3" runat="server" text="Internal Greeting" /> Here, the closing tag is omitted, and instead a closing / is supplied within the tag itself to indicate that the tag is closed. Throughout the book we will use this latter notation in preference to having a closing tag. Let's look at an example to set the color of a text message to red as follows (download file Ch03\Demo-Label02.aspx): 66 Chapter 3 <asp:Label id="lblGreeting2" forecolor="red" text="Red Text" runat="server" /> Let's now look at an example of how you can use the <asp:Label> control to display some text for a tourism company. In this example, it's assumed that the values of the user's name and desired destination have already been passed to the server, and that all you need to do is display a message that confirms that you have received the user's details. Try It Out Using the <asp:Label> Control 1. Open ASP.NET Web Matrix and create a new folder named Ch03 within C:\BegASPNET11. Within that folder, create a new item of the type ASP.NET page named TIO-Label.aspx. Enter code as needed to create the following page. Some lines are pre-typed for you by Web ASP.NET Web Matrix. (You can learn basic techniques for working with ASP.NET Web Matrix in Appendix B.) <html> <head> <title>Label Control page</title> </head> <body> <h1>Feiertag Holidays </h1> <form runat="server"> <asp:Label id="Message1" runat="server" text="Chris"></asp:Label>, you have selected to receive information about <asp:Label id="Message2" runat="server" text="Oslo"></asp:Label>. The information package will be sent to you. </form> </body> </html> 2. View it from your browser, the page should be displayed as shown in Figure 3-3: Figure 3-3 How It Works The text of your <asp:Label> that appears on the page is the same as that obtained as a result of typing it in a standard HTML <span> tag. More interestingly, take a look at the source code by selecting View | 67 Server Controls and Variables Source from your browser and notice two things. First, the ASP.DLL has processed your <asp:Label> controls into <span> tags. Second, ASP.NET has added an extra tag of name="_VIEWSTATE" to your form with its value set to a long string of characters. The VIEWSTATE tag will be discussed shortly. Modifying ASP.NET Controls Although this exercise works, it still does not give us the ability to modify the text in code. Recall from Chapter 2 where you used code in a Page_Load() event that affected controls. You can do the same here (you might want to save this file as TIO-Label2.aspx). First delete the Text attribute (shown in bold in the following code listing) at the end of both <asp:Label> controls: <asp:Label id="Message1" runat="server" text="Chris"></asp:Label> , you have selected to receive information about <asp:Label id="Message2" runat="server" text="Oslo"></asp:Label> . The information package will be sent to you. Now add the following ASP.NET script block before your HTML code: <script runat="server" Language="C#"> void Page_Load() { Message1.Text = "Vervain"; Message2.Text = "Madrid"; } </script> If you run the example again, you'll see that the output has changed to that shown in Figure 3-4: Figure 3-4 The Page_Load() section is executed whenever the page is requested or refreshed; we will discuss this in more detail in Chapter 6. Let's ignore this statement for now, it's the code it contains that's important. The following line refers to the text contained by your first <asp:Label> control. Here we're changing the Text attribute of Message1 to Vervain. Message1.Text = "Vervain" 68 Chapter 3 This example allowed you to change the contents of an <asp:Label> control by modifying code. Future chapters will discuss how to modify the values in more sophisticated ways, including changing the text to be values read from a database. All of the ASP.NET control attributes (properties) can be changed in the code in the same way. For example: Message1.Text = "Vervain" Message1.backcolor = Drawing.color.red Message1.font.italic=true Message1.font.size = FontUnit.large <asp:DropDownList> Before moving onto the <asp:DropDownList> control, let's pause to look at its HTML form control equivalent. Dropdown listboxes are a series of <option> tags within a pair of <select> tags as shown: <select name="lstCities"> <option>Madrid</option> <option>Oslo</option> <option>Lisbon</option> </select> The <asp:DropDownList> control will produce the same output when coded in the following way: <asp:DropDownList id="lstCities" runat="server"> <asp:ListItem>Madrid</asp:ListItem > <asp:ListItem >Oslo</asp:ListItem > <asp:ListItem >Lisbon</asp:ListItem > </asp:DropDownList > The three important differences between the ASP.NET control and the HTML form control are: ❑ The <asp:DropDownList> tag directly replaces the <select> tag ❑ The <asp:ListItem> tag replaces the <option> tag ❑ The id attribute replaces the name attribute Visually, the <asp:DropDownList> control is identical to the HTML dropdown list control; it's what goes on behind the scene that is different. The best way to explain this is to look at an example. Let's create a form that asks the user to select the particular holiday destination they wish to know more about. Try It Out Using the <asp:DropDownList> Control 1. Create a new ASP.NET page called TIO-DropDownList.aspx in Web Matrix and type in the following. As always with ASP.NET Web Matrix, some lines are pre-typed for you. <script runat="server" Language="C#"> void Page_Load() { if (Page.IsPostBack) 69 Server Controls and Variables lblMessage.Text = "You have selected " + list1.SelectedItem.Value; } </script> <html> <head> <title>Drop Down List Example</title> </head> <body> <asp:Label id="lblMessage" runat="server"/><br/> <form runat="server"> Which city interests you?<br /> <asp:DropDownList id="list1" runat="server"> <asp:ListItem>Madrid</asp:ListItem> <asp:ListItem>Oslo</asp:ListItem> <asp:ListItem>Lisbon</asp:ListItem> </asp:DropDownList> <input type="Submit"> </form> </body> </html> 2. Run this file in your browser and the page should be displayed as shown in Figure 3-5: Figure 3-5 3. Select Oslo and click on Submit Query. 4. Now click on View | Source. You should see something like the following; don't worry if your version isn't exactly the same – the code is tailored to your personal browser: <html> <head><title>Drop Down List Example</title></head> <body> <span id="lblMessage">You have selected Oslo</span><br/> <form name="_ctl0" method="post" action="TIO-DropDownList.aspx" id="_ctl0"> <input type="hidden" name="__VIEWSTATE" value="dDwtMTMyNTU5Mzc0Njt0PDtsPGk8MT47PjtsPHQ8cDxwPGw8VGV4dDs+O2w8WW91IGhhdmU 70 Chapter 3 gc2VsZWN0ZWQgT3Nsbzs+Pjs+Ozs+Oz4+Oz4qihTIIzJYjhyzz+oJsyJ1gevEaQ==" /> Which city interests you?<br /> <select name="list1" id="list1"> <option value="Madrid">Madrid</option> <option selected="selected" value="Oslo">Oslo</option> <option value="Lisbon">Lisbon</option> </select> <input type="Submit"> </form> </body> </html> How It Works As you can see, everything that has been sent to the browser is HTML code and text; there are no proprietary tags or script to run on the browser. Also note that this is a one-page solution, in contrast to the old two-page approach with HTML forms. This form page submits to itself. To explain how it works, we're going to reference the source code that we can view in our browser, and compare it to our original ASPX code. Let's start from the <form> section of the script. The <form runat="server"> attribute is set that tells ASP.NET to execute the form on the server. If you compare this line to what has been returned to the browser, you can see a large difference: <form name="ctrl0" method="post" action="listpage.aspx" id="ctrl0"> ASP.NET has generated four new attributes. The name and id attributes serve a similar purpose - to uniquely identify the form. However, it's the other two that are of interest. HTML forms require a page to receive the form data and a method of transmission. We didn't specify either of these in our ASPX code, so ASP.NET specified them for us by default to be the same page. It also specifies the POST method by default. The main item on the form is the <asp:DropDownList> control: Which city interests you? <br /> <asp:DropDownList id="list1" runat="server"> <asp:ListItem>Madrid</asp:ListItem> <asp:ListItem>Oslo</asp:ListItem> <asp:ListItem>Lisbon</asp:ListItem> </asp:DropDownList> It's crucial to note how this is rendered. If you view the source code that's sent back to the browser, you should see the following: <input type="hidden" name="__VIEWSTATE" value="dDwtMTMyNTU5Mzc0Njt0PDtsPGk8MT47PjtsPHQ8cDxwPGw8VGV4dDs+O2w8WW91IGhhdm Ugc2VsZWN0ZWQgT3Nsbzs+Pjs+Ozs+Oz4+Oz4qihTIIzJYjhyzz+oJsyJ1gevEaQ==" /> Which city interests you?<br /> <select name="list1" id="list1"> <option value="Madrid">Madrid</option> 71 Server Controls and Variables [...]... -4.9406564584 124 7E- 324 (for negative values), and 4.9406564584 124 7E 324 to 1.7976931348 623 2E308 (for positive values) Decimal The decimal type accepts numbers with about 28 digits, which you can allocate between the left and right side of the decimal point With zero decimal places, it can support large positive or negative numbers with up to 27 following zeros Alternatively, you can store a very accurate number with. .. numbers with decimal places The various floating point datatypes supported by C# are: ❑ float: Holds single precision floating-point numbers The float type supports values within the range -3.4 028 23E38 to -1.40 129 8E-45 (for negative values), and 1.40 129 8E-45 to 3.4 028 23E38 (for positive values) ❑ double: Holds double precision floating-point numbers The range of double is - 1.7976931348 623 2E308 to... subsequent submit, it is decoded and ASP.NET can work with the values The second half is just a HTML form control; this is the HTML output of a Note that it had one of the tags altered to reflect the selection you made before submitting the form How ASP.NET Code Works We've seen that the ASP.NET server control passes form values to the ASP.NET code Now let's see how you... structures such as if () All ASP.NET controls start with , contain the attribute runat="server", and each control has an id attribute 81 Chapter 3 Before going on to chapters with other ASP.NET features, let's pause to look more closely at how to use variables in ASP.NET pages Then we will take a closer look at the control structures in the logic being used Storing Information in C# Variables Variables... range is reduced to – 128 to + 127 ❑ short: As the name implies, can only accept a limited range of values, from – 32, 768 to + 32, 767 ❑ ushort: is like uint and can be used for unsigned (positive) numbers; since memory space is not used for the sign, the value can go up to 65,535 ❑ long: Similar to the int type, but supports a much larger range; can contain a value up to 9 ,22 3,3 72, 036,854,775,808 (that... variable // alternate formats for input MyDateTime = Convert.ToDateTime("1/1 /20 05"); MyDateTime = Convert.ToDateTime("4 :25 :05 PM"); MyDateTime = Convert.ToDateTime("16 :25 :05"); MyDateTime = Convert.ToDateTime("1/1 /20 05 16 :25 :05"); // following line fails - use 24 hour time or AM/PM but not both MyDateTime = Convert.ToDateTime("16 :25 :05 PM"); 89 Chapter 3 Boolean Boolean variables can be set to one of two... files): 96 Server Controls and Variables string strVariableGlobal = "Use me anyplace on the page"; void Page_Load() { } //end Page_Load The lifetime of a global variable begins at the start of the ASP.NET page, ends at the end of the page, and spans all functions within script In ASP.NET, you can also create variables with a scope beyond the... 2 Open it in your browser as shown in Figure 3- 12 prior to the click: Figure 3- 12 3 Add the following highlighted lines of code to declare a block variable inside a block but use it outside the block Rename the file (and later save) as TIO-VariableScope2.aspx and view the page in your browser Note the strMyBlockVariable2 not declared error as seenin Figure 3-13: . < ;asp: Label> Control 1. Open ASP. NET Web Matrix and create a new folder named Ch03 within C:BegASPNET 11. Within that folder, create a new item of the type ASP. NET page named TIO-Label.aspx more about. Try It Out Using the < ;asp: DropDownList> Control 1. Create a new ASP. NET page called TIO-DropDownList.aspx in Web Matrix and type in the following. As always with ASP. NET Web Matrix, some lines. runat="server"> < ;asp: ListItem>Madrid< /asp: ListItem > < ;asp: ListItem >Oslo< /asp: ListItem > < ;asp: ListItem >Lisbon< /asp: ListItem > < /asp: DropDownList > The three important differences between the ASP. NET

Ngày đăng: 13/08/2014, 04:21

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

Tài liệu liên quan