Download presentation
Presentation is loading. Please wait.
Published byCatherine Powers Modified over 8 years ago
1
ASP.NET Part 2 Instructor: Charles Moen CSCI/CINF 4230
2
2 The Page Class Every ASP.NET web page is created on the server as a class that inherits from System.Web.UI.Page The Page class encapsulates a single request and response for a single user; and tells us a lot about that request Your page inherits the properties of the Page class; and you can use these properties in your code ASP.NET (MacDonald, Walther)
3
3 Some Properties of the Page Class Request – an object that encapsulates information about the current request; e.g., the URL, the form data, info about the browser Response – an object that encapsulates the response that we send back to the browser Session – a collection that holds one user’s data so that it is available to that user from any page for the duration of one browser session Application – a collection shared between all users EnableViewState – whether controls will retain their state IsPostBack – whether this is the first time the page is viewed ASP.NET (MacDonald, Walther)
4
4 Using a Page Class Property Each object or collection that is a property of the Page class is available in your ASP.NET code ASP.NET (MacDonald) Response.Redirect("newpage.aspx"); The Response object that belongs to your page C# example that redirects a request to a different URL: A method of the Response object “ this. ” is implied, and can be left out
5
5 ASP.NET Controls HTML server controls (from last week) Web controls Processed on the server side ASP.NET versions of standard controls –label, button, input fields Validation controls –required field, range, regular expression Data controls –for working with data in a database Navigation controls –menus, tree views, bread crumb trails Rich controls –calendar, file upload, wizards, banner ads Login controls ASP.NET (Walther, MacDonald)
6
6 Web Controls ASP.NET elements that are processed on the server Available as objects in your server-side code The wide variety of different web controls makes it easier for the developer to create a rich user interface Standard controls Label Button TextBox Rendered on the web page as HTML elements, but each web control is not necessarily represented as a single HTML element ASP.NET (MacDonald, W3Schools) Rich controls Calendar ImageMap Wizard
7
7 Adaptive Rendering ASP.NET server controls detect the type of browser that sent the request The HTML code returned to the browser is tailored for that particular browser JavaScript may be added, as long as the browser supports it ASP.NET (Walther)
8
8 Label Control ASP.NET (Walther, MacDonald) Used for displaying text on a page Its text can be changed by your code Rendered in the browser as a span element protected void Page_Load(object sender, EventArgs e) { Label1.Text = "Hello"; } The asp namespace identifies this element as an ASP.NET web control The id attribute is needed so that you can use the element in your code All ASP.NET web controls need runat="server" The Text property is set on the server side here, before the response is sent to the browser
9
9 Label Control (continued) ASP.NET (Walther, MacDonald) Text placed between the opening and closing tags will be assigned to its Text property Hello It has many properties that can be set in the code or in the Properties panel in Visual Studio BackColorBorderStyleFont BorderColorBorderWidthForeColor It’s better to use a style sheet and set the CssClass property
10
10 TextBox Control ASP.NET (Walther, MacDonald) Used for getting input from the user The TextMode property can also be set to “ Multiline ” for a multiline text area or to “ Password ” for a field where the input is hidden and usually represented as a line of bullets Rendered in the browser as one of the following, depending on the value of the TextMode attribute
11
11 Button Control ASP.NET (Walther, MacDonald) Used for submitting a form to the server In Visual Studio, all web controls can be dragged from the Toolbox onto the Design view of the page In Visual Studio, if you double-click on a Button in the Design view, the onclick property will be set to an event handler in the code-behind file. With AutoEventWireup, the name of the event handler will be named with the value of the button id attribute, followed by the event name.
12
12 Page_Load Event ASP.NET (MacDonald) public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } The event handler Fires every time the page is sent from the browser to the server Used for initializing values in elements on the page Can be added by double-clicking in the white space of the page in the Design view
13
13 Demo Page_Load ASP.NET (MacDonald) Demo Page Load
14
14 Demo Page_Load ASP.NET (MacDonald) using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { nameLabel.Text = "Hello " + nameTextBox.Text; } Double-click on the Button in the Design view to add a handler for its Click event. Then add the code that assigns the value of the TextBox to the Label when the form is submitted.
15
15 Demo Page_Load ASP.NET (MacDonald) using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { nameTextBox.Text = "Type your name"; } protected void Button1_Click(object sender, EventArgs e) { nameLabel.Text = "Hello " + nameTextBox.Text; } Now add some code to initialize the Text in the TextBox. What happens when you overstrike the instructions with your name and click on the button? HINT: The Page_Load event occurs before any other events on this page.
16
16 IsPostBack Property ASP.NET (Walther, MacDonald) Property of the Page class Returns a boolean value false – this is the first time the page is viewed true – this page is loaded as a result of the user clicking on a control on the page
17
17 Demo Page_Load ASP.NET (MacDonald) using System; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { nameTextBox.Text = "Type your name"; } protected void Button1_Click(object sender, EventArgs e) { nameLabel.Text = "Hello " + nameTextBox.Text; } Before initializing the TextBox, test whether this is the first time the page is viewed by testing the value of the IsPostBack property of the page
18
18 Sandwich Builder Demo ASP.NET (Walther, MacDonald) Use ASP.NET and Visual Studio 2008 to build a web application similar to the application in Bonus Lab 4
19
19 DropDownList Control ASP.NET (Walther, MacDonald) One of many ASP.NET list controls Similar to the select element in HTML Allows the user to select a single item from a list Please select one... Roast Beef Ham Turkey The asp namespace identifies these elements as ASP.NET web controls The DropDownList element contains ListItem elements, each of which has a Value attribute, as well as a Text property, shown as the text inside the tags Only the DropDownList element has an id and a runat="server" attribute
20
20 Handler for the Button Control ASP.NET (Walther, MacDonald) Double-click on the Button to add a handler for its click event Sends a request to the server; and adds text to the label public partial class _Default : System.Web.UI.Page { protected void orderSandwichButton_Click(object sender, EventArgs e) { yourSandwichLabel.Text = quantityTextBox.Text; yourSandwichLabel.Text += " " + meatDropDownList.SelectedItem.Value; } Use the SelectedItem property to find the user’s selection
21
21 RadioButtonList Control ASP.NET (Walther, MacDonald) Works the same way as the DropDownList But it’s rendered differently in the HTML Cheese No cheese We can specify which LIstItem is selected by default
22
22 Handler for the Button Control ASP.NET (Walther, MacDonald) Testing the selected item of the RadioButtonList public partial class _Default : System.Web.UI.Page { protected void orderSandwichButton_Click(object sender, EventArgs e) { yourSandwichLabel.Text = quantityTextBox.Text; yourSandwichLabel.Text += " " + meatDropDownList.SelectedItem.Value; if (cheeseRadioButtonList.SelectedItem.Text == "Cheese") { yourSandwichLabel.Text += ", " + "cheese"; }
23
23 CheckBoxList Control ASP.NET (Walther, MacDonald) Allows the user to select multiple items from a list Has an Items collection as a property Lettuce Tomato Onion
24
24 Handler for the Button Control ASP.NET (Walther, MacDonald) Find all the selected ListItems by iterating through the Items collection of the CheckBoxList public partial class _Default : System.Web.UI.Page { protected void orderSandwichButton_Click(object sender, EventArgs e) { yourSandwichLabel.Text = quantityTextBox.Text; yourSandwichLabel.Text += " " + meatDropDownList.SelectedItem.Value; if (cheeseRadioButtonList.SelectedItem.Text == "Cheese") { yourSandwichLabel.Text += ", " + "cheese"; } foreach (ListItem item in veggiesCheckBoxList.Items) { if (item.Selected == true) { yourSandwichLabel.Text += ", " + item.Value; }
25
25 C# Loops Three types of loops in C# for loop while loop foreach loop Looping with foreach Useful for examining each item in a collection It’s read-only – the values in the collection cannot be changed in the loop ASP.NET (MacDonald) foreach (ListItem item in veggiesCheckBoxList.Items) { if (item.Selected == true) { yourSandwichLabel.Text += ", " + item.Value; } The collection A local variable of the same type as the data stored in the collection
26
26 Sandwich Builder Demo ASP.NET (Walther, MacDonald) It would be nice to show the selections made by users before they click on “Order Sandwich” As soon as the user makes a selection from the DropDownList, we want the selected value to show up in the Label
27
27 Handler for the DropDownList Control ASP.NET (Walther, MacDonald) In the Design view, double-click on the DropDownList to add a handler for its default event protected void meatDropDownList_SelectedIndexChanged(object sender, EventArgs e) { yourSandwichLabel.Text += meatDropDownList.SelectedValue; } This event handler will be called whenever the user makes a selection from the DropDownList We add this code so that the selected value will be added to the Label control, and it will be visible on the web page <asp:DropDownList ID="meatDropDownList" runat="server" onselectedindexchanged="meatDropDownList_SelectedIndexChanged"> This attribute is added to the DropDownList control to call the event handler
28
28 PostBack Sending another request for the same page back to the server Can be used to create the illusion that a web page has a rich UI Makes it possible for the server to respond to small events on the page, such as when the user enters new input in a TextBox when the user makes a change in a DropDownList The big idea: When a user interacts with a control on your web page, your application will react immediately ASP.NET (MacDonald, Walther)
29
29 Automatic PostBack The problem: All ASP.NET server controls are processed only on the server, and the web page contains only standard HTML Some events, such as the click event of a Button control, will trigger an immediate postback, so that the event handler can respond to the user’s action; however, actions such as selecting from a DropDownList do not trigger a postback Automatic postback Force a control to post back the page immediately as a result of a particular user action Set the AutoPostBack property to true ASP.NET (MacDonald, Walther)
30
30 DropDownList Control ASP.NET (Walther, MacDonald) <asp:DropDownList ID="meatDropDownList" runat="server" AutoPostBack="True" onselectedindexchanged="meatDropDownList_SelectedIndexChanged"> Please select one... Roast Beef Ham Turkey When AutoPostBack is true, a new request for this page will be sent to the server as soon as the user changes the selection
31
31 Adding Validation ASP.NET (Walther, MacDonald) We need to check whether a quantity was entered and whether the user selected the meat ingredient
32
32 Validation Controls ASP.NET controls that automate the validation of user input Five types RequiredFieldValidator RangeValidator CompareValidator RegularExpressionValidator CustomValidator One or more validation controls can be bound to a single input control Depending on the browser, ASP.NET may add code for client-side validation, but it always validates on the server ASP.NET (MacDonald)
33
33 RequiredFieldValidator ASP.NET (Walther, MacDonald) Drag the validator from the Toolbox to the page in the Design view Set the ErrorMessage property Set the ControlToValidate property <asp:RequiredFieldValidator ID="quantityRequiredFieldValidator1" runat="server" ControlToValidate="quantityTextBox" ErrorMessage="Please enter a quantity">
34
34 CompareValidator ASP.NET (Walther, MacDonald) Drag the validator from the Toolbox to the page in the Design view Set the ErrorMessage property Set the ControlToValidate property Set the Operator property to “NotEqual” Set the ValueToCompare property to “Please select one…” Set the Type property to string <asp:CompareValidator ID="meatCompareValidator" runat="server" ControlToValidate="meatDropDownList" ErrorMessage="Please select a meat item" Operator="NotEqual“ ValueToCompare="Please select one...">
35
35 RangeValidator ASP.NET (Walther, MacDonald) Drag the validator from the Toolbox to the page in the Design view Set the ErrorMessage property Set the ControlToValidate property Set the Maximum property to “NotEqual” Set the MinimumValue property to “Please select one…” Set the Type property to Integer <asp:RangeValidator ID="quantityRangeValidator" runat="server" ControlToValidate="quantityTextBox" ErrorMessage="Enter a number > 1" MaximumValue="100" MinimumValue="1" Type="Integer"> Remember to set the Type property!
36
State Management
37
37 State Management Storing the data that your web application needs The problems Thousands of users can be using the same web application at the same time, so we need to be concerned about having sufficient memory and keeping track of each user’s data All users of the application communicate with it over a stateless HTTP connection Five choices View state Query string Cookies Session state Application state ASP.NET (MacDonald)
38
38 View State Storing the data in a hidden form field Scope A single page Typical use Storing the state of the form elements on a page Your code can store data in view state and then retrieve it during the postback Problems Limited scope; increases the page size ASP.NET (MacDonald) Data is stored as a Base64 encoded string
39
39 View State Example A page with a single TextBox that stores a counter ASP.NET (MacDonald, Walther) Demo View State 0 public partial class _Default : System.Web.UI.Page { protected void btnAdd_Click(object sender, EventArgs e) { lblCounter.Text = (Int32.Parse(lblCounter.Text) + 1).ToString(); }
40
40 View State Example From the source on the client side ASP.NET (MacDonald, Walther) Initial value After one postback
41
41 Cookies in ASP.NET Storing the data in a cookie Scope Any page in your application Can be stored between visits by setting the Expires property Typical use Storing preferences Storing the signin name in Homework #3, Phase II Problems Users may disable cookies in the browser ASP.NET (MacDonald)
42
42 Cookie Example Two pages that use a cookie for the user’s favorite color ASP.NET (MacDonald) <asp:Button ID="submitButton" runat="server" onclick="submitButton_Click" Text="Submit" /> SecondPage.aspx
43
43 Cookie Example Two pages that use a cookie for the user’s favorite color ASP.NET (MacDonald) Default.aspx
44
44 Cookie Example ASP.NET (MacDonald) public partial class _Default : System.Web.UI.Page { protected void submitButton_Click(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["color"]; if (cookie == null) { cookie = new HttpCookie("color"); } cookie["color"] = favoriteColorTextBox.Text; Response.Cookies.Add(cookie); } public partial class SecondPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["color"]; if (cookie == null) { favoriteColorLabel.Text = "No favorite color"; } else { favoriteColorLabel.Text = "Favorite color = " + cookie["color"]; }
45
45 References Ding, Wei, “ASP.NET” UHCL lecture slides, 2008. MacDonald, Matthew, Beginning ASP.NET 3.5 in C# 2008: From Novice to Professional, Second Edition. Apress, 2007. Walther, Stephen. ASP.NET 3.5 Unleashed. SAMS, 2008. W3Schools Online Web Tutorials. “ASP.NET”. [Online]. Available: http://www.w3schools.com/aspnet/default.asp
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.