ASP.NET Part 2 by bzs12927

VIEWS: 86 PAGES: 45

									CSCI/CINF 4230




                     ASP.NET
                         Part 2




                 Instructor: Charles Moen
ASP.NET (MacDonald, Walther)‫‏‬

                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


                                                                 2
ASP.NET (MacDonald, Walther)‫‏‬

   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

                                                                            3
ASP.NET (MacDonald)‫‏‬

            Using a Page Class Property

    Each object or collection that is a property of the Page class is
     available in your ASP.NET code

   C# example that redirects a request to a different URL:

     Response.Redirect("newpage.aspx");




  “this.” is implied,   The Response            A method of the
  and can be left out   object that belongs     Response object
                        to your page




                                                                         4
ASP.NET (Walther, MacDonald)‫‏‬

               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
                                                           5
ASP.NET (MacDonald, W3Schools)‫‏‬

                    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   Rich controls
          • Label             • Calendar
          • Button            • ImageMap
          • TextBox           • Wizard

    Rendered on the web page as HTML elements, but each
     web control is not necessarily represented as a single
     HTML element                                           6
ASP.NET (Walther)‫‏‬

            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




                                                               7
ASP.NET (Walther, MacDonald)‫‏‬

                             Label Control

     Used for displaying text on a page
     Its text can be changed by your code
     Rendered in the browser as a span element
     <asp:Label id="Label1" runat="server" />


   The asp namespace         The id attribute is                                   All ASP.NET web
   identifies this element   needed so that you can    The Text property is        controls need
   as an ASP.NET web         use the element in your   set on the server side      runat="server"
   control                   code                      here, before the response
                                                       is sent to the browser

     protected void Page_Load(object sender, EventArgs e)
     {
         Label1.Text = "Hello";
     }

                                                                                                     8
ASP.NET (Walther, MacDonald)‫‏‬

             Label Control (continued)

    Text placed between the opening and closing tags will be assigned
     to its Text property
    <asp:Label id="Label1" runat="server">Hello</asp:Label>



    It has many properties that can be set in the code or in the
     Properties panel in Visual Studio
       BackColor     BorderStyle   Font
       BorderColor   BorderWidth   ForeColor

    It’s better to use a style sheet and set the CssClass property

    <asp:Label id="Label1" runat="server" CssClass="myStyle" />


                                                                         9
ASP.NET (Walther, MacDonald)‫‏‬

                  TextBox Control

    Used for getting input from the user

    <asp:TextBox id="signin" runat="server" TextMode="SingleLine" />



                                         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
       <input id="signin" type="text" />
       <input id="signin" type="password" />
       <textarea id="signin" rows="2" cols="20" />
                                                                                       10
ASP.NET (Walther, MacDonald)‫‏‬

                     Button Control

    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

    <asp:Button id="Button1" runat="server" Text="Button" onclick="Button1_Click" />




                                   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.


                                                                                                     11
ASP.NET (MacDonald)‫‏‬

                      Page_Load Event

    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

    public partial class _Default : System.Web.UI.Page         The event handler
    {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

    }




                                                                            12
ASP.NET (MacDonald)‫‏‬

                       Demo Page_Load
 <%@ Page Language="C#" AutoEventWireup="true"   CodeFile="Default.aspx.cs"
 Inherits="_Default" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
     <title>Demo Page Load</title>
 </head>
 <body>
     <form id="form1" runat="server">
     <div>

         <asp:TextBox ID="nameTextBox" runat="server"></asp:TextBox>
         <br />
         <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

         <br />
         <asp:Label ID="nameLabel" runat="server"></asp:Label>

     </div>
     </form>
 </body>
 </html>




                                                                                            13
ASP.NET (MacDonald)‫‏‬

                       Demo Page_Load

    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.


                                                                                                        14
ASP.NET (MacDonald)‫‏‬

                       Demo Page_Load

    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.                                       15
ASP.NET (Walther, MacDonald)‫‏‬

           IsPostBack Property

    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




                                                                            16
ASP.NET (MacDonald)‫‏‬

                       Demo Page_Load

    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



                                                                                                          17
ASP.NET (Walther, MacDonald)‫‏‬

       Sandwich Builder Demo

    Use ASP.NET and Visual Studio 2008 to build a web application
     similar to the application in Bonus Lab 4




                                                                     18
ASP.NET (Walther, MacDonald)‫‏‬

             DropDownList Control

    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

     <asp:DropDownList ID="meatDropDownList" runat="server">
       <asp:ListItem>Please select one...</asp:ListItem>
       <asp:ListItem Value="roast beef">Roast Beef</asp:ListItem>
       <asp:ListItem Value="ham">Ham</asp:ListItem>
       <asp:ListItem Value="turkey">Turkey</asp:ListItem>
     </asp:DropDownList>

                                                         Only the DropDownList element has an
                                                         id and a runat="server" attribute
   The asp namespace
   identifies these elements   The DropDownList element contains ListItem
   as ASP.NET web controls     elements, each of which has a Value attribute, as
                               well as a Text property, shown as the text inside the
                               tags
                                                                                                19
ASP.NET (Walther, MacDonald)‫‏‬

Handler for the Button Control

    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




                                                                                          20
ASP.NET (Walther, MacDonald)‫‏‬

      RadioButtonList Control

    Works the same way as the DropDownList
    But it’s rendered differently in the HTML


    <asp:RadioButtonList ID="cheeseRadioButtonList" runat="server">
      <asp:ListItem Selected="True">Cheese</asp:ListItem>
      <asp:ListItem>No cheese</asp:ListItem>
    </asp:RadioButtonList>




                       We can specify which LIstItem is
                       selected by default




                                                                      21
ASP.NET (Walther, MacDonald)‫‏‬

Handler for the Button Control

    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";
            }
        }
    }




                                                                                   22
ASP.NET (Walther, MacDonald)‫‏‬

          CheckBoxList Control

    Allows the user to select multiple items from a list
    Has an Items collection as a property


    <asp:CheckBoxList ID="veggiesCheckBoxList" runat="server">
      <asp:ListItem Value="lettuce">Lettuce</asp:ListItem>
      <asp:ListItem Value="tomato">Tomato</asp:ListItem>
      <asp:ListItem Value="onion">Onion</asp:ListItem>
    </asp:CheckBoxList>




                                                                 23
ASP.NET (Walther, MacDonald)‫‏‬

Handler for the Button Control

    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;
                }
            }
        }
    }
                                                                                   24
ASP.NET (MacDonald)‫‏‬

                               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

               A local variable of the same type as
               the data stored in the collection           The collection

      foreach (ListItem item in veggiesCheckBoxList.Items)
      {
        if (item.Selected == true)
        {
          yourSandwichLabel.Text += ", " + item.Value;
        }
      }
                                                                                      25
ASP.NET (Walther, MacDonald)‫‏‬

       Sandwich Builder Demo

    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




                                                                               26
ASP.NET (Walther, MacDonald)‫‏‬

 Handler for the DropDownList Control

    In the Design view, double-click on the DropDownList to add a
     handler for its default event
    <asp:DropDownList ID="meatDropDownList" runat="server"
    onselectedindexchanged="meatDropDownList_SelectedIndexChanged">


    This attribute is added to the DropDownList      This event handler will be called whenever the
    control to call the event handler                user makes a selection from the DropDownList


    protected void meatDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        yourSandwichLabel.Text += meatDropDownList.SelectedValue;
    }




       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                                      27
ASP.NET (MacDonald, Walther)‫‏‬

                          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
                                                                            28
ASP.NET (MacDonald, Walther)‫‏‬

             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

                                                                            29
ASP.NET (Walther, MacDonald)‫‏‬

           DropDownList Control



    <asp:DropDownList ID="meatDropDownList" runat="server" AutoPostBack="True"
    onselectedindexchanged="meatDropDownList_SelectedIndexChanged">
      <asp:ListItem>Please select one...</asp:ListItem>
      <asp:ListItem Value="roast beef">Roast Beef</asp:ListItem>
      <asp:ListItem Value="ham">Ham</asp:ListItem>
      <asp:ListItem Value="turkey">Turkey</asp:ListItem>
    </asp:DropDownList>


                                                     When AutoPostBack is true, a new
                                                     request for this page will be sent to the
                                                     server as soon as the user changes the
                                                     selection



                                                                                                 30
ASP.NET (Walther, MacDonald)‫‏‬

              Adding Validation

    We need to check whether a quantity was entered and whether the
     user selected the meat ingredient




                                                                       31
ASP.NET (MacDonald)‫‏‬

                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
                                                                                32
ASP.NET (Walther, MacDonald)‫‏‬

       RequiredFieldValidator

    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"></asp:RequiredFieldValidator>




                                                                           33
ASP.NET (Walther, MacDonald)‫‏‬

                CompareValidator

      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..."></asp:CompareValidator>
                                                                            34
ASP.NET (Walther, MacDonald)‫‏‬

                   RangeValidator

      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 &gt; 1"
    MaximumValue="100"
    MinimumValue="1"
    Type="Integer"></asp:RangeValidator>

               Remember to set the Type property!
                                                                            35
State Management
ASP.NET (MacDonald)‫‏‬

               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
                                                                                        37
ASP.NET (MacDonald)‫‏‬

                           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

    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
    value="/wEPDwUJNjk5Mjk5OTQ0ZGTcEFyGL3cyxi1gghJtim8OseVCtQ==" />



                     Data is stored as a Base64 encoded string
                                                                                            38
ASP.NET (MacDonald, Walther)‫‏‬

                  View State Example

      A page with a single TextBox that stores a counter
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Demo View State</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

       <asp:Button ID="btnAdd" runat="server" onclick="btnAdd_Click" Text="Add" />
       &nbsp;
       <asp:Label ID="lblCounter" runat="server">0</asp:Label>

       <br />

    </div>                       public partial class _Default : System.Web.UI.Page
    </form>                      {
</body>                              protected void btnAdd_Click(object sender, EventArgs e)
</html>                              {
                                         lblCounter.Text = (Int32.Parse(lblCounter.Text) + 1).ToString();
                                     }
                                 }



                                                                                                        39
ASP.NET (MacDonald, Walther)‫‏‬

                    View State Example

    From the source on the client side

    Initial value
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
      value="/wEPDwUJNjk5Mjk5OTQ0ZGTcEFyGL3cyxi1gghJtim8OseVCtQ==" />




    After one postback
      <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
      value="/wEPDwUJNjk5Mjk5OTQ0D2QWAgIDD2QWAgIDDw8WAh4EVGV4dAUBMWRkZA1FuTOyb8IhS1SU+Hs9kPOsCCWN" />




                                                                                                        40
ASP.NET (MacDonald)‫‏‬

             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




                                                                         41
ASP.NET (MacDonald)‫‏‬

                         Cookie Example

      Two pages that use a cookie for the user’s favorite color
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Label ID="favoriteColorLabel" runat="server" Text="Favorite color:"></asp:Label>
        &nbsp;<asp:TextBox ID="favoriteColorTextBox" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="submitButton" runat="server" onclick="submitButton_Click"
            Text="Submit" />
        <br />
        <br />
        <a href="SecondPage.aspx">SecondPage.aspx</a>
    </div>
    </form>
</body>
</html>



                                                                                                42
ASP.NET (MacDonald)‫‏‬

                         Cookie Example

      Two pages that use a cookie for the user’s favorite color
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="favoriteColorLabel" runat="server"></asp:Label>
        <br />
        <br />
        <a href="Default.aspx">Default.aspx</a>
    </div>
    </form>
</body>
</html>




                                                                         43
ASP.NET (MacDonald)‫‏‬

                         Cookie Example
 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"];
                             }
                         }
                     }
                                                                                                     44
                       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




                                                                                 45

								
To top