SlideShare ist ein Scribd-Unternehmen logo
1 von 98
Downloaden Sie, um offline zu lesen
HOW ASP.NET WORKS
2
Overview
2


       ASP.NET Event Model
       ASP.NET Code Compilation
       The P  Class
            Page 

       ASP.NET Application Lifecycle
Event Model
3


       One of the key features of ASP.NET is that it uses an
        event-based programming model.
       In the simple Hello World example, we added a small
                  p                   p ,
        bit of programming to a method named Page_Load.
         This method is an event handler.
         An event handler is a method that determines what actions
          are performed when an event occurs, such as when the user
          clicks a button or selects an item from a list.
         When an event is raised, the handler for that specific event
          is executed.
Event Handlers
4


       In the .NET Framework, all event handlers have a
        specific method signature, that is, a specific return
        type and parameters.
         yp       p
         Event handlers are always void methods.
         Event handlers always accept two parameters:
           an object parameter
           an EventArgs parameter
                  (or
                   ( a subclass of EventArgs, such as CommandEventArgs or
                          bl     f               h          d
                   ImageClickEventArgs).

           protected void Page_Load(object sender, EventArgs e)
           protected void Page Load(object sender, EventArgs e)
           {
              …
           }
ASP.NET Event System
                   y
5


       The event system in ASP.NET operates in a different
        manner than in a Windows application or from the
        event system in browser-based Javascript.
               y                              p
         In a Windows application, for instance, events are
          raised and handled on the same processor.
         In contrast, ASP.NET events are raised on the client (the
          browser) but transmitted to and handled on the server.
           Si
            Since     its event h dli requires a round-trip to the server,
                      i         handling    i          d i      h
               ASP.NET offers a smaller set of events in comparison to a
               totally client-based event system.
ASP.NET Event System
                   y
6
7   HTTP P
         Protocol
                l
    A Di
      Digression
             i
HTTP
8


       Communication protocol for the web
       Current version HTTP/1.1
HTTP
9


       An HTTP session is a sequence of network request-
                               q                   q
        response transactions.
         An     HTTP client initiates a request.
           Itestablishes a Transmission Control Protocol (TCP) connection
            to a particular port on a host (typically port 80)
         An HTTP server listening o that po wa s for a client's
                   se ve s e g on a port waits o c e s
          request message.
           Upon       receiving the request, the server sends back
                    a status line, such as "HTTP/1 1 200 OK , and
                              line           HTTP/1.1     OK"
                    a message of its own, the body of which is perhaps the
                     requested resource, an error message, or some other information.
HTTP Requests
            q
10


        An HTML page, once received, typically will invoke
         subsequent HTTP requests for other resources:
           <img src="someimage.gif" />
              g             g g     /
           <link href="somestyles.css" />
           <script src="somecode.js" />
           <embed src= someflash.swf  />
           <embed src="someflash swf" />
HTTP Example 1
     E    l
1. User makes request
                q
2. Browser sends HTTP request to server

    Request Line   GET /comp1274/randyc/lab10done/enter_country.htm HTTP/1.1
                   Accept: */*
                   Accept‐Language: en‐us,en‐ca;q=0.5
                   Accept‐Encoding: gzip, deflate
Request Header     User Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; 
                   User‐Agent: Mozilla/4 0 (compatible; MSIE 6 0; Windows NT 5 1; SV1;  NET CLR 1 1 4322; 
                   InfoPath.1; .NET CLR 2.0.50727)
                   Host: csweb2.mtroyal.ca
                   Connection: Keep‐Alive
     Blank line




                                                         HTTP
                                                        Request

                             Browser
                               owse                                               Web Server
                                                                                      Se ve
3. Server receives and processes the HTTP request


                       HTTP
                      Request
       Browser                       Web Server




                                     Retrieve
                                   Requested file
4. Server sends HTTP response back
                          p
Response Line + Status Code   HTTP/1.1 200 OK
                              Server: Microsoft‐IIS/5.0
                              Date: Thu, 30 Mar 2006 19:50:54 GMT
                              Content‐Type: text/html
        Response Header
                              Accept Ranges: bytes
                              Accept‐Ranges: bytes
                              Last‐Modified: Fri, 24 Mar 2006 17:50:50 GMT
                              Content‐Length: 209
                Blank line

                              <html><head><title>Enter A Country</title></head>
                              <body>
                              <form method="post" action="form_filter.asp">
                              Enter Country Search: 
                                          y                                       Server
         Response Content
                              <input type="text" name="search"><p>
                              <input type="submit">                                 HTTP
                              </form>                                              Response
                              </body></html>


                                                                                  Browser
5. Browser displays response
              p y      p
6. User submits data
7. Browser sends HTTP request to server

POST /comp1274/randyc/lab10done/form_filter.asp HTTP/1.1
Accept: */*
A    t  */*
Referer: http://csweb2.mtroyal.ca/comp1274/randyc/lab10done/enter_country.htm
Accept‐Language: en‐us,en‐ca;q=0.5
Content‐Type: application/x‐www‐form‐urlencoded
C t t T          li ti /        f      l    d d
Accept‐Encoding: gzip, deflate
User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 
                                        )
1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
Host: csweb2.mtroyal.ca
Content‐Length: 13
Connection: Keep‐Alive
Cache‐Control: no‐cache


Search=Canada


         User entered form data goes here in the http request header (because form
         method="post") as a series of name=value pairs (called a querystring)
What if method=get rather than post?

<form method="get" action="form_filter.asp">


Then the user entered form data is added to the requested URL
GET /comp1274/randyc/lab10done/form_filter.asp?Search=Canada HTTP/1.1



Versus

<form method="post" action="form_filter.asp">

Then the user entered form data is added to the end of HTTP request header
POST /comp1274/randyc/lab10done/form_filter.asp HTTP/1.1
rest of HTTP request header goes here


Search=Canada
8. Server receives and processes the HTTP request


                       HTTP
                      Request
      Browser                       Web Server




                                 Server processes
                                   the request
                                    h
9. Server script generates response sent back to
  browser

HTTP/1.1 200 OK
Server: Microsoft‐IIS/5.0
Date: Thu, 30 Mar 2006 19:51:06 GMT
Content‐Length: 164
Content‐Type: text/html
Cache‐control: private


<html><head><title>reading recordsets</title></head>
<body>
<h2>countries</h2>
<table border=1>
<tr><td>2</td><td>canada</td></tr>
</table>
</body></html>
 /b d   /ht l
10. Browser displays the response
               p y          p
HTTP Example 2
     E    l
1. User makes request
                q
2. Browser sends HTTP request to server

GET /comp1274/randyc/lab10done/data_browser.asp HTTP/1.1
Accept: */*
Accept‐Language: en‐us,en‐ca;q=0.5
Accept‐Encoding: gzip, deflate
User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 
1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
Host: csweb2.mtroyal.ca
Connection: Keep‐Alive
3. Server receives and processes the HTTP request


                       HTTP
                      Request
      Browser                       Web Server




                                 Server processes
                                   the request
                                    h
4. Server script generates response sent back to browser

HTTP/1.1 200 OK
Server: Microsoft‐IIS/5.0
S       Mi     ft IIS/5 0
Date: Thu, 30 Mar 2006 19:51:06 GMT
Content‐Length: 1590
Content Type: text/html
Content‐Type: text/html
Cache‐control: private


<html><head><title>Data Browser</title></head>
<body>
<h1>SELECT * FROM movies WHERE runtime < 90<h1>
<table border=1>
      <tr>
         <td><b>Title</b></td>
              <td><b>Release Date</b></td>
              <td><b>Run Time</b></td>      
      </tr>
...
5. Browser displays the response
              p y          p
6. User makes request (click on a link)
                q     (               )
7. Browser sends HTTP request to server

GET /comp1274/randyc/lab10done/movie.asp?ID=84 HTTP/1.1
Accept: */*
Referer: http://csweb2.mtroyal.ca/comp1274/randyc/lab10done/data_browser.asp
Accept‐Language: en‐us,en‐ca;q=0.5
Accept‐Encoding: gzip, deflate
User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 
1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
Host: csweb2.mtroyal.ca
                 y
Connection: Keep‐Alive
8. Server receives request, processes it, and generates response


HTTP/1.1 200 OK
Server: Microsoft‐IIS/5.0
Date: Thu, 30 Mar 2006 19:51:06 GMT
Content‐Length: 585
Content‐Type: text/html
                  /h l
Cache‐control: private


<html><head><title>nightmare before christmas, the</title></head>
<html><head><title>nightmare before christmas  the</title></head>
<body>
<h1>Nightmare Before Christmas, The</h1>
Directed by <b>Henry Selick</b><br/>
Released on  12/9/1994<br/>
Movie length is 76 minutes
<h2>Summary</h2>
...
9. Browser displays the response
              p y          p
HTTP Example 3
     E    l
1. User makes request
                q
2. Browser sends HTTP request to server

GET /comp1274/randyc/lab10done/does_not_exist.asp HTTP/1.1
Accept: */*
Accept‐Language: en‐us,en‐ca;q=0.5
Accept‐Encoding: gzip, deflate
User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 
1.1.4322; InfoPath.1; .NET CLR 2.0.50727)
Host: csweb2.mtroyal.ca
Connection: Keep‐Alive
3. Server receives and processes the HTTP request


                       HTTP
                      Request
       Browser                       Web Server




                                  Server processes
                                    the request
4. Server receives request, processes it, and generates response


HTTP/1.1 404 Object Not Found
Server: Microsoft‐IIS/5.0
         i     f     /
Date: Thu, 30 Mar 2006 19:51:06 GMT
Content‐Length: 4040
Content Type: text/html
Content‐Type: text/html
Cache‐control: private


<html>
...
<title>The page cannot be found</title>
...
<body>
<table>
...
The page you are looking for might have been removed, had its 
The page you are looking for might have been removed  had its 
...
5. Browser displays the response
              p y          p
Examining HTTP
             g
39


                                        Google Chrome




            FireFox Firebug Extension
40   Back ASPNET
     B k to ASP.NET
     Digression over …
     Di     i
ASP.NET Event Handling
                          g
41


        How then does ASP.NET communicate the triggering
         of an event on one machine (the client browser’s) to
         another machine (the server hosting the page)?
                          (                g     p g )
          Answer   1:
            Through   HTTP
          Answer   2:
            Through   querystring parameters sent via HTTP
          Answer   3:
            Through   postback
Postback
42


        Postback is the process by which the browser posts
         information back to itself.
          That is, p
                  , posts information back to the server by
                                                          y
           requesting the same page.
          That is, it is simply a HTTP POST request for the same
           ASP.NET page
Postback
43

 <body>                                                              EventTest.aspx (on server)
 <form id= form1  runat= server >
 <form id="form1" runat="server">
       Please enter your name:
       <asp:TextBox ID="name" runat="server" /><br />
       Choose favorite author:
       <asp:DropDownList ID="myList" runat="server" >
          <asp:ListItem>Choose an author</asp:ListItem>
          <asp:ListItem>Atwood</asp:ListItem>
          <asp:ListItem>Austin</asp:ListItem>
          <asp:ListItem>Hawthorne</asp:ListItem>
          <asp:ListItem>Melville</asp:ListItem>
       </asp:DropDownList><br />
       <asp:Button ID="btnEnter" runat="server" Text=“Enter“
              OnClick=“btnEnter_Click" />
       <p><asp:Label ID="msg1" runat="server" /></p>
       <p><asp:Label ID "msg1" runat "server" /></p>
 </form>
 </body>



                                                                          Result in browser
                              <body>
                              <form name="form1" method="post" action="EventTest.aspx" id="form1">

                              <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
Q: Which page will be            value="/wEPDwUJMzU4OTQyMTQyD2QWAgIDD2Q …
requested when the user       …
                              <input type="submit" name="btnEnter" value="Submit" id="btnEnter" />
presses the submit button?    <p><span id="msg1">In Page_Load<br/></span></p>
                              …
Postback
44


        Postback in ASP.NET
          only occurs within web forms (i.e., within a form element
           with runat="server"), and
          only server control events cause a post back.

        Each cycle in which information is displayed then
               y                               p y
         posted back to the server, and then redisplayed
         again, is sometimes also called a postback round
         trip.
Postback
45


        In other words, it is postback which makes it possible
         for browser-based events (e.g., clicking a button,
         choosing from a list) to be handled on the web
                 g             )
         server.
Postback
46
Event Types
            yp
47


        Two types
          Page    events
            Always
                 y   triggered and always in a certain specific order (see
                        gg             y                p             (
             Page Lifecycle).
            Triggered and handled on the server.
                  Thus
                   Th no postback involved
                            tb k i l d
          Control   events
            Associated  with particular controls and only triggered in
             certain circumstances.
                  Requires postback
Postback and Events
48


        How does the server “know” that a request is a
                                know
         postback request (i.e., a request in which a control
         event will have to be handled)?
                                       )
          By   the presence of the viewstate variable.
HTTP + Postback
49

                                                                        First request for page (from URL, or link, bookmark, …)
1
     GET http://localhost:53372/Chapter2/EventTest.aspx


     NOTE: since this is the first request, there are no querystring parameters in the request



2    Page executes on the server.
     HTTP/1.1 200 OK
     Server: ASP.NET Development Server/9.0.0.0
     Date: Tue, 21 Sep 2010 18:52:36 GMT
     Content‐Length: 2039
     C t t       th 2039
     Content‐Type: text/html

     <html xmlns="http://www.w3.org/1999/xhtml">
     <head><title>Event Test</title></head>
     <body>
     <form name="form1" method="post" action="EventTest.aspx" id="form1">
     <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
                value="/wEPDwUJMzU4 …
     ...

     The generated HTTP response (above) for request contains hidden viewstate
HTTP + Postback
50



3
     GET http://localhost:53372/Chapter2/EventTest.aspx
     …                                                                               Second request for page
     Name=Randy&myList=Melvillee&__VIEWSTATE=/wEPDwUJMzU4…                           (from user clicking button)

     NOTE: since this is the postback request, there are querystring parameters in the request header,
     one of which is the viewstate (as well as user’s form data)
                                               user s



4    HTTP/1.1 200 OK
     Server: ASP.NET Development Server/9.0.0.0
     Date: Tue, 21 Sep 2010 18:52:36 GMT
     Date: Tue  21 Sep 2010 18:52:36 GMT
     Content‐Length: 2039
     Content‐Type: text/html
                                                                                         Server can figure out that this is
     <html xmlns="http://www.w3.org/1999/xhtml">                                         a postback request from the
     <head><title>Event Test</title></head>                                              presence of the viewstate
                                                                                                           iewstate
     <body>
     <form name="form1" method="post" action="EventTest.aspx" id="form1">
                                                                                         querystring parameter
     <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
                value="/wEPDwUJMzU4 …
     ...

     HTTP Response for this postback request still contains hidden, but probably modified, viewstate
View State
51


        View state is one of the most important features of
         ASP.NET.
        It is a specially encoded string that is used to retain
         page and form information between requests and is
         sent to the browser within a hidden HTML <input>
         element.
        All page elements not posted back via the standard
         HTTP POST mechanism are stored within this string.
         <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
            value= /wEPDwUJODExMDE5NzY5D2QWAgIDD2QWAgIBDw8WAh4EVGV4dAUKMDgvMDE
            value "/wEPDwUJODExMDE5NzY5D2QWAgIDD2QWAgIBDw8WAh4EVGV4dAUKMDgvMDE
              vMjAwNmRkZDZPhFHJER4chf3nmlgfL+uq4W58" />
View State
52


        View state is a mechanism for preserving display
         state within web forms.
        Recall that HTTP is by nature stateless.
          This means that after the server responds to a request,
           it no longer preserves any data used for that request.
        Nonetheless, web applications very frequently need
         to retain state on a page between requests.
View State
53


        View state is generated once all the page code has
         executed but before the response is rendered.
        The value of each web server control on the page is
         serialized into text as a number of Base64-
         encoded triplets, one of which contains a name-
                     p
         value pair.
          Serialize = convert programming object into some type
           of text representation.
        This view state string is then output to the browser
         as a hidden <input> element named "__VIEWSTATE".
View State
54


        When the form is posted back, ASP.NET receives the
         view state (since it was contained in a form
         element), deserializes this information and restores
                 ),
         the state of all the controls prior to the post.
          Deserialize = convert some type of text representation
           back into a programming object.
        ASP.NET updates the state of the controls based on
         the data that has just been posted back, and then
         calls the usual page and control event handlers.
View State
55


        Since the details of encoding and decoding values
         from the view state are handled by the ASP.NET
         runtime, y can g
                 , you     generally ignore the view state
                                   y g
         and simply enjoy its benefits.
Viewstate
56


        However, sometimes a developer may wish to turn
         off the view state for a page.
          For instance, if a very large data set is being
                       ,         y g                     g
           displayed, the view state will also be quite large, which
           may significantly lengthen the time it takes the browser
           to d
              download and render the page.
                    l d d         d h
Large View State
        g
57




                        Viewstate = 277K
Turn Off Viewstate
58


        If a page is not going to post back to itself, you can
         improve page performance by disabling the view
         state for the page within the Page directive.
                       p g               g
         <%@ Page ... EnableViewState="false" %>



        You can also disable viewstate on a control-by-
                                             control by
         control basis.
         <asp:Label runat="server" ID="Label2" ViewStateMode="Disabled" ... />
Disabling Viewstate
             g
59




                           viewstate = 0.05 K
Disabling Viewstate
             g
60


        Do remember that viewstate is required for any
         type of postback (control-event) processing.
        Again, you only want to disable it for pages or
         controls that don’t need it.
Page Life Cycle
       g        y
61


        Page and control events occur in a certain order
         which we can call the page life cycle.
        Five general stages:
          Page initialization
          Loading

          Postback control event handling

          Renderingg
          Unloading
Complete Page Life Cycle
        p       g        y
62
Event Handlers
63


        Within each of these stages, the ASP.NET page
         raises events that you can handle in your code.
        For most situations, you only need to worry about
         the Page_Load event and certain control events.
Event Handlers
64


           Because page events always happen, you simply need to
                    p g              y    pp , y       py
            define a page event handler by using the appropriate
            naming convention:
                Page_XXXX
                 Page XXXX   where XXXX is the event name
           Control events need to be explicitly wired.
                i.e., you must explicitly bind the handler method to the event.
                This can be done declaratively in the markup (the usual case),

     <asp: utto
     <asp:Button id="btnSubmit" runat="server" 
                  d bt Sub t     u at se e
        OnClick="btnSubmit_Click" />



                or programmatically in the code (rare).
     btnSubmit.Click += new EventHandler( this.btnSubmit_Click );
Adding Event Handlers in VS
          g
65
Detecting Postback
             g
66


        There are times when you may want your page to
         behave differently the very first time it is requested.
          One   typical example is that you want to read and
                  yp         p           y
           display values from a database in a list only the first
           time the page is requested.
          In subsequent postbacks, the data is preserved by the
           view state so there is no need to re-read the database.
Detecting Postback
             g
67


        Your page can test if it is being requested for the
         first time via the IsPostBack property
          Thisp p y
               property is equal to false if the page is being
                            q                    p g         g
           requested for the first time.
          protected void Page_Load(object sender, EventArgs e)
          {
             …
             if (! IsPostBack)
             {
                // Do something here for very first request
             }
             …
          }
Postback and Non-Postback Controls
68


        Button-type controls with Click events always generate
         an immediate postback to the server.
        But not all control events generate an immediate
         postback.
        In fact, most control events by default do not cause a
         postback.
          Some controls—for i
           S           l f instance, a Label control—never can
                                                   l
           cause a postback.
          Change events also do not generate a postback, by
           default.
           d f lt
                An example of a change event is selecting an item from a drop-
                 down list or entering text into a text box.
Change Events
         g
69


        You may be able to enable postback for change-
                                                      change
         type events by setting the control’s AutoPostBack
         p p y
         property to true.
          e.g., you could change the previous example so that the
           DropDownList control automatically causes a postback.

          By doing so, you could eliminate the button completely
           and instead do your message processing in the event
           handler for the S l t dI d Ch d event
                             SelectedIndexChanged event.
Without AutoPostBack
70




           Notice: label didn’t change
                         didn t



                                         Notice: selection event not handled until the button
                                         click triggered a postback
With AutoPostBack
71




             Notice: label changed because list
             selection triggered a postback




                                                  Notice: button click also triggered postback but
                                                  only button click event handler is executed.
AutoPostBack
72

<fieldset>
    <legend>Sample Form ‐ Testing Autopostback</legend>
    <p><label>Address: </label><br /> 
    <asp:TextBox ID="txtAddress" runat="server" /></p>
    <p><label>Country: </label><br />
    <asp:DropDownList ID="drpCountry" runat="server" AutoPostBack="true"
        onselectedindexchanged="drpCountry_SelectedIndexChanged">
        <asp:ListItem>United States</asp:ListItem>
        <asp:ListItem>Canada</asp:ListItem>
    </asp:DropDownList></p>
    <p><label>
      <asp:Literal ID="litZipOrPostal" runat="server" Text="Zip: " />
    </label> <br />
    <asp:TextBox ID="txtZipOrPostal" runat="server" /></p>
    <asp:Button ID "btnSubmit" runat "server" Text "Submit" 
                ID="btnSubmit" runat="server" Text="Submit" 
        onclick="btnSubmit_Click" />
</fieldset>
                                                       protected void Page_Load(object o, EventArgs e)
<asp:Label ID="labMessage" runat="server" />
                                                       {
                                                           labMessage.Text = "In page load<br/>";
                                                       }
                                                       protected void drpCountry_SelectedIndexChanged(object o, EventArgs e)
                                                          t t d  id d C      t   S l t dI d Ch       d( bj t   E    tA     )
                                                       {
                                                           labMessage.Text += "In country select event handler<br/>";
                                                           if (drpCountry.SelectedValue == "Canada")
                                                               litZipOrPostal.Text = "Postal Code";
                                                           else if (drpCountry.SelectedValue == "United States")
                                                               litZipOrPostal.Text = "Zipcode";
                                                                                      Zipcode ;
                                                       }
                                                       protected void btnSubmit_Click(object sender, EventArgs e)
                                                       {
                                                           labMessage.Text += "In button event handler<br/>";
                                                       }
Visually Detecting Postback
            y         g
73




1

          2   Browser will go blank at start of any new HTTP
              GET or POST request (including a postback
              request) and/or will be request delay.

              When testing a web site locally, this can happen     3   Postback request finished rendering in browser.
              too quickly to notice, but will be noticeable when
              hosted on a real remote web server (especially a
              busy one).
Visually Detecting Postback
            y         g
74




           Normal postback request always incurs a delay
           because it is a round trip
                           round-trip:
           • request (across internet),
           • execute, (on server),
           • response (across internet),
           • render in browser.
Using AJAX
         g
75


        It is possible to asynchronously make a postback
         request using ASP.NET’s AJAX abilities.
          This avoids the blank screen and wait of a full postback
                                                           p
           request.
          Instead, the browser will make the request “in the
           background”using asynchronous Javascript (AJAX).
76   ASP.NET
     ASPNET AJAX
     Another Di
     A h Digression
                i
ASP.NET AJAX
   ASP.NET AJAX adds Asynchronous JavaScript and
    XML (AJAX) support to ASP.NET.
   ASP.NET AJAX was up until the fall of 2006 was
    known by the code-known of Atlas.
ASP.NET AJAX
   AJAX is not a product.
     Rather it is the most common name given to a style of
      web development that makes fuller use of Javascript
      and the browser Document Object Model (DOM) in the
      construction of web application user interfaces.
ASP.NET AJAX
   AJAX web applications also make use of all the
    current browsers’ ability to asynchronously request
    and receive information from the browser
    independently of the usual page request/page
    receive/page display cycle.
     Thisability to asynchronously communicate with the
      server makes it possible to create pages that are more
      responsive and l di
             i      d less disruptive.
                                 ti
Normal web application client-server interaction
AJAX web application client-server interaction
ASP.NET AJAX Examples
                 p
                                                             Here client-side only (no communication
                                                             with server) Javascript is being used to
                                                              ih        )J       i i b i         d
                                                             provide a richer user experience.




      Here the browser is communicating asynchronously with
      the server (the loading animation tells the user this) in
      order to provide a list of relevant search terms.

      Javascript is being used to make the request and
      receive the d
               h data b k in either XML or JSON format.
                        back      h                 f
AJAX
   Asynchronous communication is typically achieved in
      y                            yp     y
    Javascript using the XMLHttpRequest object (though
    some sites use hidden IFrame elements instead).
     This bj t
      Thi object was initially offered i I t
                      i iti ll ff d in Internet E l
                                                 t Explorer 5 as an
      ActiveX component;
     FireFox, Opera, and Safari subsequently have added
      native support for XMLHttpRequest.
     However, since Internet Explorer 5 and 6 XMLHttpRequest
      support is via an ActiveX component, it is possible for the
        pp                           p      ,    p
      user to disable it via browser settings.
     Internet Explorer 7, like the other browsers now supports
      XMLHttpRequest natively
                        natively.
AJAX
   While richer AJAX web applications are a real
    boon for the user, creating them can be a real
    nightmare for the developer.
      g                       p
     Javascript as a language lacks the kind of object-
      oriented features developers expect.
     As well, Javascript can be quite difficult to debug.

     As a consequence, there has been a proliferation of
      frameworks and toolkits to simplify the process of
      f         k    d     lk         lf h              f
      developing AJAX applications.
Why AJAX Applications Are Good
  y       pp
   Fewer roundtrips
   Less bandwidth
     only   need to transfer info/markup that needs updating
   Less work for the web server
   More responsive for the user
Why AJAX Applications Are Bad
  y       pp
   Accessibility problems
     Often   don’t work very well with screen readers.
   Can be harder to develop
   Can be a nightmare to debug
AJAX at Work
87




                                                                        Only these areas were
                                                                        “updated” creating the
                                                                        illusion of better
1                                                                       responsiveness




                2   Notice: no obvious round-trip (though request +
                    execution + response did happen, it just happened
                                   p             pp , j        pp
                    in the background asynchronously).
ASP.NET AJAX Coding
                       g
88

     <form id="form1" runat="server">                                                           Ensures appropriate
                                                                                                Javascript libraries are sent
     <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
                                                                                                to browser.
     <asp:UpdatePanel ID="UpdatePanel1" runat="server">
         <ContentTemplate>                                                                      Any postback requests within
             <fieldset>                                                                         this UpdatePanel will be done
                 <legend>Sample Form ‐ Testing Autopostback</legend>
                                                                                                asynchronously.
                                                                                                   y          y
                 <p><label>Address: </label><br /> 
                 <asp:TextBox ID="txtAddress" runat="server" /></p>
                 <p><label>Country: </label><br />
                 <asp:DropDownList ID="drpCountry" runat="server" AutoPostBack="true"
                     onselectedindexchanged="drpCountry_SelectedIndexChanged">
                     <asp:ListItem>United States</asp:ListItem>
                        p                           p
                     <asp:ListItem>Canada</asp:ListItem>
                 </asp:DropDownList></p>
                 <p><label><asp:Literal ID="litZipOrPostal" runat="server" Text="Zip: " /></label> <br />
                 <asp:TextBox ID="txtZipOrPostal" runat="server" /></p>
                 <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
                     onclick="btnSubmit_Click" />
             </fieldset>
              /fi ld t
             <asp:Label ID="labMessage" runat="server" />
         </ContentTemplate>
     </asp:UpdatePanel>

     </form>
89   ASP.NET B hi d h S
     ASPNET Behind the Scenes
     Warning: Advanced Stuff Ahead
     W i Ad           d S ff Ah d
     (you may want to wait until later to cover this)
ASP.NET Behind the Scenes
90


        What happens when the browser requests an
                 pp                      q
         ASP.NET web page?
        Quick Answer
          the  visual elements of the page are parsed into a class,
          this class, along with its code is dynamically compiled
           (into MSIL)
           (i t MSIL),
          This MSIL is JIT compiled and then executed on the
           server, ,
          Execution produces the HTML and Javascript that is then
           sent to the browser.
ASP.NET 2.0 Compilation Process
                    p
91
Where is this stuff?
92


          The path for the generated class files created from
           the web forms along with the temporary assemblies
           is
               [.NET System Directory]Temporary ASP.NET Files[virtual 
                directory][x][y] 
              where x and y are randomly-generated names.
             For instance, the path for the assembly on my
              development server was
     C:WINDOWSMicrosoft.NETFrameworkv4.0.30319Temporary ASP.NET Fileschapter27229f9fd8d0746a9.
Parsed Class (created by ASP.NET from web form)
93
Page class
       g
94


        All Web forms ultimately inherit from the Page class,
         which is defined in the System.Web.UI namespace.
ASP.NET 2.0 Class Inheritance
95
Page class
       g
96


        The Page class inherits from the TemplateControl class,
         which in turn inherits from the Control class.
        As a result, the Page class provides a great deal of
         functionality exposed as properties and methods
         that you can make use of in your web forms.
               y                        y
        Some of these properties are analogous to the
         intrinsic global objects of ASP classic, such as Request,
         Response, Session, and Server.
Application Lifecycle
      pp              y
97


        The page life cycle is just one of several processing
         steps which occur as part of the larger ASP.NET life
         cycle.
          y
Application Lifecycle
      pp              y
98

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (19)

jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
AJAX Transport Layer
AJAX Transport LayerAJAX Transport Layer
AJAX Transport Layer
 
Data Access Mobile Devices
Data Access Mobile DevicesData Access Mobile Devices
Data Access Mobile Devices
 
Html server control - ASP. NET with c#
Html server control - ASP. NET with c#Html server control - ASP. NET with c#
Html server control - ASP. NET with c#
 
Introduction to Ajax programming
Introduction to Ajax programmingIntroduction to Ajax programming
Introduction to Ajax programming
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Programming Server side with Sevlet
 Programming Server side with Sevlet  Programming Server side with Sevlet
Programming Server side with Sevlet
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Url programming
Url programmingUrl programming
Url programming
 
Jquery Ajax
Jquery AjaxJquery Ajax
Jquery Ajax
 
Ajax
AjaxAjax
Ajax
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Asp.net
Asp.netAsp.net
Asp.net
 
Ajax
AjaxAjax
Ajax
 
Asp.net By Durgesh Singh
Asp.net By Durgesh SinghAsp.net By Durgesh Singh
Asp.net By Durgesh Singh
 
Programming web application
Programming web applicationProgramming web application
Programming web application
 
State management
State managementState management
State management
 

Andere mochten auch

Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overviewukdpe
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015Hossein Zahed
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1Hossein Zahed
 
Microsoft SQL Server 2008
Microsoft SQL Server 2008Microsoft SQL Server 2008
Microsoft SQL Server 2008Hossein Zahed
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life CycleAbhishek Sur
 

Andere mochten auch (9)

HTML & XHTML Basics
HTML & XHTML BasicsHTML & XHTML Basics
HTML & XHTML Basics
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015ASP.NET MVC 5 - EF 6 - VS2015
ASP.NET MVC 5 - EF 6 - VS2015
 
CSharp Language Overview Part 1
CSharp Language Overview Part 1CSharp Language Overview Part 1
CSharp Language Overview Part 1
 
Big Data World
Big Data WorldBig Data World
Big Data World
 
SEO Fundamentals
SEO FundamentalsSEO Fundamentals
SEO Fundamentals
 
Microsoft SQL Server 2008
Microsoft SQL Server 2008Microsoft SQL Server 2008
Microsoft SQL Server 2008
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 

Ähnlich wie Web II - 02 - How ASP.NET Works

Ähnlich wie Web II - 02 - How ASP.NET Works (20)

Web I - 05 - HTTP Protocol
Web I - 05 - HTTP ProtocolWeb I - 05 - HTTP Protocol
Web I - 05 - HTTP Protocol
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009
 
Web Services 2009
Web Services 2009Web Services 2009
Web Services 2009
 
HTTP fundamentals for developers
HTTP fundamentals for developersHTTP fundamentals for developers
HTTP fundamentals for developers
 
Under the Covers with the Web
Under the Covers with the WebUnder the Covers with the Web
Under the Covers with the Web
 
Http request&response
Http request&responseHttp request&response
Http request&response
 
Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)Unit 02: Web Technologies (2/2)
Unit 02: Web Technologies (2/2)
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
5-WebServers.ppt
5-WebServers.ppt5-WebServers.ppt
5-WebServers.ppt
 
Appl layer
Appl layerAppl layer
Appl layer
 
Http-protocol
Http-protocolHttp-protocol
Http-protocol
 
Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014Http request&response by Vignesh 15 MAR 2014
Http request&response by Vignesh 15 MAR 2014
 
Web Real-time Communications
Web Real-time CommunicationsWeb Real-time Communications
Web Real-time Communications
 
PHP Training: Module 1
PHP Training: Module 1PHP Training: Module 1
PHP Training: Module 1
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Web server
Web serverWeb server
Web server
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
HTTP Protocol Basic
HTTP Protocol BasicHTTP Protocol Basic
HTTP Protocol Basic
 
Cgi
CgiCgi
Cgi
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 

Mehr von Randy Connolly

Ten-Year Anniversary of our CIS Degree
Ten-Year Anniversary of our CIS DegreeTen-Year Anniversary of our CIS Degree
Ten-Year Anniversary of our CIS DegreeRandy Connolly
 
Careers in Computing (2019 Edition)
Careers in Computing (2019 Edition)Careers in Computing (2019 Edition)
Careers in Computing (2019 Edition)Randy Connolly
 
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...Randy Connolly
 
Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)Randy Connolly
 
Modern Web Development (2018)
Modern Web Development (2018)Modern Web Development (2018)
Modern Web Development (2018)Randy Connolly
 
Helping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing DisciplinesHelping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing DisciplinesRandy Connolly
 
Constructing a Web Development Textbook
Constructing a Web Development TextbookConstructing a Web Development Textbook
Constructing a Web Development TextbookRandy Connolly
 
Web Development for Managers
Web Development for ManagersWeb Development for Managers
Web Development for ManagersRandy Connolly
 
Disrupting the Discourse of the "Digital Disruption of _____"
Disrupting the Discourse of the "Digital Disruption of _____"Disrupting the Discourse of the "Digital Disruption of _____"
Disrupting the Discourse of the "Digital Disruption of _____"Randy Connolly
 
17 Ways to Fail Your Courses
17 Ways to Fail Your Courses17 Ways to Fail Your Courses
17 Ways to Fail Your CoursesRandy Connolly
 
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...Randy Connolly
 
Constructing and revising a web development textbook
Constructing and revising a web development textbookConstructing and revising a web development textbook
Constructing and revising a web development textbookRandy Connolly
 
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
Computing is Not a Rock Band: Student Understanding of the Computing DisciplinesComputing is Not a Rock Band: Student Understanding of the Computing Disciplines
Computing is Not a Rock Band: Student Understanding of the Computing DisciplinesRandy Connolly
 
Citizenship: How do leaders in universities think about and experience citize...
Citizenship: How do leaders in universities think about and experience citize...Citizenship: How do leaders in universities think about and experience citize...
Citizenship: How do leaders in universities think about and experience citize...Randy Connolly
 
Thinking About Technology
Thinking About TechnologyThinking About Technology
Thinking About TechnologyRandy Connolly
 
A longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission dataA longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission dataRandy Connolly
 
Is Human Flourishing in the ICT World of the Future Likely?
Is Human Flourishing in the ICT World of the Future Likely?Is Human Flourishing in the ICT World of the Future Likely?
Is Human Flourishing in the ICT World of the Future Likely?Randy Connolly
 
Constructing a Contemporary Textbook
Constructing a Contemporary TextbookConstructing a Contemporary Textbook
Constructing a Contemporary TextbookRandy Connolly
 

Mehr von Randy Connolly (20)

Ten-Year Anniversary of our CIS Degree
Ten-Year Anniversary of our CIS DegreeTen-Year Anniversary of our CIS Degree
Ten-Year Anniversary of our CIS Degree
 
Careers in Computing (2019 Edition)
Careers in Computing (2019 Edition)Careers in Computing (2019 Edition)
Careers in Computing (2019 Edition)
 
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
 
Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)
 
Modern Web Development (2018)
Modern Web Development (2018)Modern Web Development (2018)
Modern Web Development (2018)
 
Helping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing DisciplinesHelping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing Disciplines
 
Constructing a Web Development Textbook
Constructing a Web Development TextbookConstructing a Web Development Textbook
Constructing a Web Development Textbook
 
Web Development for Managers
Web Development for ManagersWeb Development for Managers
Web Development for Managers
 
Disrupting the Discourse of the "Digital Disruption of _____"
Disrupting the Discourse of the "Digital Disruption of _____"Disrupting the Discourse of the "Digital Disruption of _____"
Disrupting the Discourse of the "Digital Disruption of _____"
 
17 Ways to Fail Your Courses
17 Ways to Fail Your Courses17 Ways to Fail Your Courses
17 Ways to Fail Your Courses
 
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
 
Constructing and revising a web development textbook
Constructing and revising a web development textbookConstructing and revising a web development textbook
Constructing and revising a web development textbook
 
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
Computing is Not a Rock Band: Student Understanding of the Computing DisciplinesComputing is Not a Rock Band: Student Understanding of the Computing Disciplines
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
 
Citizenship: How do leaders in universities think about and experience citize...
Citizenship: How do leaders in universities think about and experience citize...Citizenship: How do leaders in universities think about and experience citize...
Citizenship: How do leaders in universities think about and experience citize...
 
Thinking About Technology
Thinking About TechnologyThinking About Technology
Thinking About Technology
 
A longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission dataA longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission data
 
Web Security
Web SecurityWeb Security
Web Security
 
Is Human Flourishing in the ICT World of the Future Likely?
Is Human Flourishing in the ICT World of the Future Likely?Is Human Flourishing in the ICT World of the Future Likely?
Is Human Flourishing in the ICT World of the Future Likely?
 
Constructing a Contemporary Textbook
Constructing a Contemporary TextbookConstructing a Contemporary Textbook
Constructing a Contemporary Textbook
 
CSS: Introduction
CSS: IntroductionCSS: Introduction
CSS: Introduction
 

Kürzlich hochgeladen

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 

Kürzlich hochgeladen (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 

Web II - 02 - How ASP.NET Works

  • 2. Overview 2  ASP.NET Event Model  ASP.NET Code Compilation  The P  Class Page   ASP.NET Application Lifecycle
  • 3. Event Model 3  One of the key features of ASP.NET is that it uses an event-based programming model.  In the simple Hello World example, we added a small p p , bit of programming to a method named Page_Load.  This method is an event handler.  An event handler is a method that determines what actions are performed when an event occurs, such as when the user clicks a button or selects an item from a list.  When an event is raised, the handler for that specific event is executed.
  • 4. Event Handlers 4  In the .NET Framework, all event handlers have a specific method signature, that is, a specific return type and parameters. yp p  Event handlers are always void methods.  Event handlers always accept two parameters:  an object parameter  an EventArgs parameter  (or ( a subclass of EventArgs, such as CommandEventArgs or bl f h d ImageClickEventArgs). protected void Page_Load(object sender, EventArgs e) protected void Page Load(object sender, EventArgs e) { … }
  • 5. ASP.NET Event System y 5  The event system in ASP.NET operates in a different manner than in a Windows application or from the event system in browser-based Javascript. y p  In a Windows application, for instance, events are raised and handled on the same processor.  In contrast, ASP.NET events are raised on the client (the browser) but transmitted to and handled on the server.  Si Since its event h dli requires a round-trip to the server, i handling i d i h ASP.NET offers a smaller set of events in comparison to a totally client-based event system.
  • 7. 7 HTTP P Protocol l A Di Digression i
  • 8. HTTP 8  Communication protocol for the web  Current version HTTP/1.1
  • 9. HTTP 9  An HTTP session is a sequence of network request- q q response transactions.  An HTTP client initiates a request.  Itestablishes a Transmission Control Protocol (TCP) connection to a particular port on a host (typically port 80)  An HTTP server listening o that po wa s for a client's se ve s e g on a port waits o c e s request message.  Upon receiving the request, the server sends back  a status line, such as "HTTP/1 1 200 OK , and line HTTP/1.1 OK"  a message of its own, the body of which is perhaps the requested resource, an error message, or some other information.
  • 10. HTTP Requests q 10  An HTML page, once received, typically will invoke subsequent HTTP requests for other resources: <img src="someimage.gif" /> g g g / <link href="somestyles.css" /> <script src="somecode.js" /> <embed src= someflash.swf  /> <embed src="someflash swf" />
  • 12. 1. User makes request q
  • 13. 2. Browser sends HTTP request to server Request Line GET /comp1274/randyc/lab10done/enter_country.htm HTTP/1.1 Accept: */* Accept‐Language: en‐us,en‐ca;q=0.5 Accept‐Encoding: gzip, deflate Request Header User Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322;  User‐Agent: Mozilla/4 0 (compatible; MSIE 6 0; Windows NT 5 1; SV1;  NET CLR 1 1 4322;  InfoPath.1; .NET CLR 2.0.50727) Host: csweb2.mtroyal.ca Connection: Keep‐Alive Blank line HTTP Request Browser owse Web Server Se ve
  • 14. 3. Server receives and processes the HTTP request HTTP Request Browser Web Server Retrieve Requested file
  • 15. 4. Server sends HTTP response back p Response Line + Status Code HTTP/1.1 200 OK Server: Microsoft‐IIS/5.0 Date: Thu, 30 Mar 2006 19:50:54 GMT Content‐Type: text/html Response Header Accept Ranges: bytes Accept‐Ranges: bytes Last‐Modified: Fri, 24 Mar 2006 17:50:50 GMT Content‐Length: 209 Blank line <html><head><title>Enter A Country</title></head> <body> <form method="post" action="form_filter.asp"> Enter Country Search:  y Server Response Content <input type="text" name="search"><p> <input type="submit"> HTTP </form> Response </body></html> Browser
  • 16. 5. Browser displays response p y p
  • 18. 7. Browser sends HTTP request to server POST /comp1274/randyc/lab10done/form_filter.asp HTTP/1.1 Accept: */* A t  */* Referer: http://csweb2.mtroyal.ca/comp1274/randyc/lab10done/enter_country.htm Accept‐Language: en‐us,en‐ca;q=0.5 Content‐Type: application/x‐www‐form‐urlencoded C t t T   li ti / f l d d Accept‐Encoding: gzip, deflate User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR  ) 1.1.4322; InfoPath.1; .NET CLR 2.0.50727) Host: csweb2.mtroyal.ca Content‐Length: 13 Connection: Keep‐Alive Cache‐Control: no‐cache Search=Canada User entered form data goes here in the http request header (because form method="post") as a series of name=value pairs (called a querystring)
  • 19. What if method=get rather than post? <form method="get" action="form_filter.asp"> Then the user entered form data is added to the requested URL GET /comp1274/randyc/lab10done/form_filter.asp?Search=Canada HTTP/1.1 Versus <form method="post" action="form_filter.asp"> Then the user entered form data is added to the end of HTTP request header POST /comp1274/randyc/lab10done/form_filter.asp HTTP/1.1 rest of HTTP request header goes here Search=Canada
  • 20. 8. Server receives and processes the HTTP request HTTP Request Browser Web Server Server processes the request h
  • 21. 9. Server script generates response sent back to browser HTTP/1.1 200 OK Server: Microsoft‐IIS/5.0 Date: Thu, 30 Mar 2006 19:51:06 GMT Content‐Length: 164 Content‐Type: text/html Cache‐control: private <html><head><title>reading recordsets</title></head> <body> <h2>countries</h2> <table border=1> <tr><td>2</td><td>canada</td></tr> </table> </body></html> /b d /ht l
  • 22. 10. Browser displays the response p y p
  • 24. 1. User makes request q
  • 25. 2. Browser sends HTTP request to server GET /comp1274/randyc/lab10done/data_browser.asp HTTP/1.1 Accept: */* Accept‐Language: en‐us,en‐ca;q=0.5 Accept‐Encoding: gzip, deflate User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR  1.1.4322; InfoPath.1; .NET CLR 2.0.50727) Host: csweb2.mtroyal.ca Connection: Keep‐Alive
  • 26. 3. Server receives and processes the HTTP request HTTP Request Browser Web Server Server processes the request h
  • 27. 4. Server script generates response sent back to browser HTTP/1.1 200 OK Server: Microsoft‐IIS/5.0 S  Mi ft IIS/5 0 Date: Thu, 30 Mar 2006 19:51:06 GMT Content‐Length: 1590 Content Type: text/html Content‐Type: text/html Cache‐control: private <html><head><title>Data Browser</title></head> <body> <h1>SELECT * FROM movies WHERE runtime < 90<h1> <table border=1> <tr> <td><b>Title</b></td> <td><b>Release Date</b></td> <td><b>Run Time</b></td>       </tr> ...
  • 28. 5. Browser displays the response p y p
  • 29. 6. User makes request (click on a link) q ( )
  • 30. 7. Browser sends HTTP request to server GET /comp1274/randyc/lab10done/movie.asp?ID=84 HTTP/1.1 Accept: */* Referer: http://csweb2.mtroyal.ca/comp1274/randyc/lab10done/data_browser.asp Accept‐Language: en‐us,en‐ca;q=0.5 Accept‐Encoding: gzip, deflate User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR  1.1.4322; InfoPath.1; .NET CLR 2.0.50727) Host: csweb2.mtroyal.ca y Connection: Keep‐Alive
  • 31. 8. Server receives request, processes it, and generates response HTTP/1.1 200 OK Server: Microsoft‐IIS/5.0 Date: Thu, 30 Mar 2006 19:51:06 GMT Content‐Length: 585 Content‐Type: text/html /h l Cache‐control: private <html><head><title>nightmare before christmas, the</title></head> <html><head><title>nightmare before christmas  the</title></head> <body> <h1>Nightmare Before Christmas, The</h1> Directed by <b>Henry Selick</b><br/> Released on  12/9/1994<br/> Movie length is 76 minutes <h2>Summary</h2> ...
  • 32. 9. Browser displays the response p y p
  • 34. 1. User makes request q
  • 35. 2. Browser sends HTTP request to server GET /comp1274/randyc/lab10done/does_not_exist.asp HTTP/1.1 Accept: */* Accept‐Language: en‐us,en‐ca;q=0.5 Accept‐Encoding: gzip, deflate User‐Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR  1.1.4322; InfoPath.1; .NET CLR 2.0.50727) Host: csweb2.mtroyal.ca Connection: Keep‐Alive
  • 36. 3. Server receives and processes the HTTP request HTTP Request Browser Web Server Server processes the request
  • 37. 4. Server receives request, processes it, and generates response HTTP/1.1 404 Object Not Found Server: Microsoft‐IIS/5.0 i f / Date: Thu, 30 Mar 2006 19:51:06 GMT Content‐Length: 4040 Content Type: text/html Content‐Type: text/html Cache‐control: private <html> ... <title>The page cannot be found</title> ... <body> <table> ... The page you are looking for might have been removed, had its  The page you are looking for might have been removed  had its  ...
  • 38. 5. Browser displays the response p y p
  • 39. Examining HTTP g 39 Google Chrome FireFox Firebug Extension
  • 40. 40 Back ASPNET B k to ASP.NET Digression over … Di i
  • 41. ASP.NET Event Handling g 41  How then does ASP.NET communicate the triggering of an event on one machine (the client browser’s) to another machine (the server hosting the page)? ( g p g )  Answer 1:  Through HTTP  Answer 2:  Through querystring parameters sent via HTTP  Answer 3:  Through postback
  • 42. Postback 42  Postback is the process by which the browser posts information back to itself.  That is, p , posts information back to the server by y requesting the same page.  That is, it is simply a HTTP POST request for the same ASP.NET page
  • 43. Postback 43 <body> EventTest.aspx (on server) <form id= form1  runat= server > <form id="form1" runat="server"> Please enter your name: <asp:TextBox ID="name" runat="server" /><br /> Choose favorite author: <asp:DropDownList ID="myList" runat="server" > <asp:ListItem>Choose an author</asp:ListItem> <asp:ListItem>Atwood</asp:ListItem> <asp:ListItem>Austin</asp:ListItem> <asp:ListItem>Hawthorne</asp:ListItem> <asp:ListItem>Melville</asp:ListItem> </asp:DropDownList><br /> <asp:Button ID="btnEnter" runat="server" Text=“Enter“ OnClick=“btnEnter_Click" /> <p><asp:Label ID="msg1" runat="server" /></p> <p><asp:Label ID "msg1" runat "server" /></p> </form> </body> Result in browser <body> <form name="form1" method="post" action="EventTest.aspx" id="form1"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"  Q: Which page will be value="/wEPDwUJMzU4OTQyMTQyD2QWAgIDD2Q … requested when the user … <input type="submit" name="btnEnter" value="Submit" id="btnEnter" /> presses the submit button? <p><span id="msg1">In Page_Load<br/></span></p> …
  • 44. Postback 44  Postback in ASP.NET  only occurs within web forms (i.e., within a form element with runat="server"), and  only server control events cause a post back.  Each cycle in which information is displayed then y p y posted back to the server, and then redisplayed again, is sometimes also called a postback round trip.
  • 45. Postback 45  In other words, it is postback which makes it possible for browser-based events (e.g., clicking a button, choosing from a list) to be handled on the web g ) server.
  • 47. Event Types yp 47  Two types  Page events  Always y triggered and always in a certain specific order (see gg y p ( Page Lifecycle).  Triggered and handled on the server.  Thus Th no postback involved tb k i l d  Control events  Associated with particular controls and only triggered in certain circumstances.  Requires postback
  • 48. Postback and Events 48  How does the server “know” that a request is a know postback request (i.e., a request in which a control event will have to be handled)? )  By the presence of the viewstate variable.
  • 49. HTTP + Postback 49 First request for page (from URL, or link, bookmark, …) 1 GET http://localhost:53372/Chapter2/EventTest.aspx NOTE: since this is the first request, there are no querystring parameters in the request 2 Page executes on the server. HTTP/1.1 200 OK Server: ASP.NET Development Server/9.0.0.0 Date: Tue, 21 Sep 2010 18:52:36 GMT Content‐Length: 2039 C t t th 2039 Content‐Type: text/html <html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Event Test</title></head> <body> <form name="form1" method="post" action="EventTest.aspx" id="form1"> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"  value="/wEPDwUJMzU4 … ... The generated HTTP response (above) for request contains hidden viewstate
  • 50. HTTP + Postback 50 3 GET http://localhost:53372/Chapter2/EventTest.aspx … Second request for page Name=Randy&myList=Melvillee&__VIEWSTATE=/wEPDwUJMzU4… (from user clicking button) NOTE: since this is the postback request, there are querystring parameters in the request header, one of which is the viewstate (as well as user’s form data) user s 4 HTTP/1.1 200 OK Server: ASP.NET Development Server/9.0.0.0 Date: Tue, 21 Sep 2010 18:52:36 GMT Date: Tue  21 Sep 2010 18:52:36 GMT Content‐Length: 2039 Content‐Type: text/html Server can figure out that this is <html xmlns="http://www.w3.org/1999/xhtml"> a postback request from the <head><title>Event Test</title></head> presence of the viewstate iewstate <body> <form name="form1" method="post" action="EventTest.aspx" id="form1"> querystring parameter <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"  value="/wEPDwUJMzU4 … ... HTTP Response for this postback request still contains hidden, but probably modified, viewstate
  • 51. View State 51  View state is one of the most important features of ASP.NET.  It is a specially encoded string that is used to retain page and form information between requests and is sent to the browser within a hidden HTML <input> element.  All page elements not posted back via the standard HTTP POST mechanism are stored within this string. <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"  value= /wEPDwUJODExMDE5NzY5D2QWAgIDD2QWAgIBDw8WAh4EVGV4dAUKMDgvMDE value "/wEPDwUJODExMDE5NzY5D2QWAgIDD2QWAgIBDw8WAh4EVGV4dAUKMDgvMDE vMjAwNmRkZDZPhFHJER4chf3nmlgfL+uq4W58" />
  • 52. View State 52  View state is a mechanism for preserving display state within web forms.  Recall that HTTP is by nature stateless.  This means that after the server responds to a request, it no longer preserves any data used for that request.  Nonetheless, web applications very frequently need to retain state on a page between requests.
  • 53. View State 53  View state is generated once all the page code has executed but before the response is rendered.  The value of each web server control on the page is serialized into text as a number of Base64- encoded triplets, one of which contains a name- p value pair.  Serialize = convert programming object into some type of text representation.  This view state string is then output to the browser as a hidden <input> element named "__VIEWSTATE".
  • 54. View State 54  When the form is posted back, ASP.NET receives the view state (since it was contained in a form element), deserializes this information and restores ), the state of all the controls prior to the post.  Deserialize = convert some type of text representation back into a programming object.  ASP.NET updates the state of the controls based on the data that has just been posted back, and then calls the usual page and control event handlers.
  • 55. View State 55  Since the details of encoding and decoding values from the view state are handled by the ASP.NET runtime, y can g , you generally ignore the view state y g and simply enjoy its benefits.
  • 56. Viewstate 56  However, sometimes a developer may wish to turn off the view state for a page.  For instance, if a very large data set is being , y g g displayed, the view state will also be quite large, which may significantly lengthen the time it takes the browser to d download and render the page. l d d d h
  • 57. Large View State g 57 Viewstate = 277K
  • 58. Turn Off Viewstate 58  If a page is not going to post back to itself, you can improve page performance by disabling the view state for the page within the Page directive. p g g <%@ Page ... EnableViewState="false" %>  You can also disable viewstate on a control-by- control by control basis. <asp:Label runat="server" ID="Label2" ViewStateMode="Disabled" ... />
  • 59. Disabling Viewstate g 59 viewstate = 0.05 K
  • 60. Disabling Viewstate g 60  Do remember that viewstate is required for any type of postback (control-event) processing.  Again, you only want to disable it for pages or controls that don’t need it.
  • 61. Page Life Cycle g y 61  Page and control events occur in a certain order which we can call the page life cycle.  Five general stages:  Page initialization  Loading  Postback control event handling  Renderingg  Unloading
  • 62. Complete Page Life Cycle p g y 62
  • 63. Event Handlers 63  Within each of these stages, the ASP.NET page raises events that you can handle in your code.  For most situations, you only need to worry about the Page_Load event and certain control events.
  • 64. Event Handlers 64  Because page events always happen, you simply need to p g y pp , y py define a page event handler by using the appropriate naming convention:  Page_XXXX Page XXXX where XXXX is the event name  Control events need to be explicitly wired.  i.e., you must explicitly bind the handler method to the event.  This can be done declaratively in the markup (the usual case), <asp: utto <asp:Button id="btnSubmit" runat="server"  d bt Sub t u at se e OnClick="btnSubmit_Click" />  or programmatically in the code (rare). btnSubmit.Click += new EventHandler( this.btnSubmit_Click );
  • 65. Adding Event Handlers in VS g 65
  • 66. Detecting Postback g 66  There are times when you may want your page to behave differently the very first time it is requested.  One typical example is that you want to read and yp p y display values from a database in a list only the first time the page is requested.  In subsequent postbacks, the data is preserved by the view state so there is no need to re-read the database.
  • 67. Detecting Postback g 67  Your page can test if it is being requested for the first time via the IsPostBack property  Thisp p y property is equal to false if the page is being q p g g requested for the first time. protected void Page_Load(object sender, EventArgs e) { … if (! IsPostBack) { // Do something here for very first request } … }
  • 68. Postback and Non-Postback Controls 68  Button-type controls with Click events always generate an immediate postback to the server.  But not all control events generate an immediate postback.  In fact, most control events by default do not cause a postback.  Some controls—for i S l f instance, a Label control—never can l cause a postback.  Change events also do not generate a postback, by default. d f lt  An example of a change event is selecting an item from a drop- down list or entering text into a text box.
  • 69. Change Events g 69  You may be able to enable postback for change- change type events by setting the control’s AutoPostBack p p y property to true.  e.g., you could change the previous example so that the DropDownList control automatically causes a postback.  By doing so, you could eliminate the button completely and instead do your message processing in the event handler for the S l t dI d Ch d event SelectedIndexChanged event.
  • 70. Without AutoPostBack 70 Notice: label didn’t change didn t Notice: selection event not handled until the button click triggered a postback
  • 71. With AutoPostBack 71 Notice: label changed because list selection triggered a postback Notice: button click also triggered postback but only button click event handler is executed.
  • 72. AutoPostBack 72 <fieldset> <legend>Sample Form ‐ Testing Autopostback</legend> <p><label>Address: </label><br />  <asp:TextBox ID="txtAddress" runat="server" /></p> <p><label>Country: </label><br /> <asp:DropDownList ID="drpCountry" runat="server" AutoPostBack="true" onselectedindexchanged="drpCountry_SelectedIndexChanged"> <asp:ListItem>United States</asp:ListItem> <asp:ListItem>Canada</asp:ListItem> </asp:DropDownList></p> <p><label> <asp:Literal ID="litZipOrPostal" runat="server" Text="Zip: " /> </label> <br /> <asp:TextBox ID="txtZipOrPostal" runat="server" /></p> <asp:Button ID "btnSubmit" runat "server" Text "Submit"  ID="btnSubmit" runat="server" Text="Submit"  onclick="btnSubmit_Click" /> </fieldset> protected void Page_Load(object o, EventArgs e) <asp:Label ID="labMessage" runat="server" /> { labMessage.Text = "In page load<br/>"; } protected void drpCountry_SelectedIndexChanged(object o, EventArgs e) t t d  id d C t S l t dI d Ch d( bj t   E tA ) { labMessage.Text += "In country select event handler<br/>"; if (drpCountry.SelectedValue == "Canada") litZipOrPostal.Text = "Postal Code"; else if (drpCountry.SelectedValue == "United States") litZipOrPostal.Text = "Zipcode";   Zipcode ; } protected void btnSubmit_Click(object sender, EventArgs e) { labMessage.Text += "In button event handler<br/>"; }
  • 73. Visually Detecting Postback y g 73 1 2 Browser will go blank at start of any new HTTP GET or POST request (including a postback request) and/or will be request delay. When testing a web site locally, this can happen 3 Postback request finished rendering in browser. too quickly to notice, but will be noticeable when hosted on a real remote web server (especially a busy one).
  • 74. Visually Detecting Postback y g 74 Normal postback request always incurs a delay because it is a round trip round-trip: • request (across internet), • execute, (on server), • response (across internet), • render in browser.
  • 75. Using AJAX g 75  It is possible to asynchronously make a postback request using ASP.NET’s AJAX abilities.  This avoids the blank screen and wait of a full postback p request.  Instead, the browser will make the request “in the background”using asynchronous Javascript (AJAX).
  • 76. 76 ASP.NET ASPNET AJAX Another Di A h Digression i
  • 77. ASP.NET AJAX  ASP.NET AJAX adds Asynchronous JavaScript and XML (AJAX) support to ASP.NET.  ASP.NET AJAX was up until the fall of 2006 was known by the code-known of Atlas.
  • 78. ASP.NET AJAX  AJAX is not a product.  Rather it is the most common name given to a style of web development that makes fuller use of Javascript and the browser Document Object Model (DOM) in the construction of web application user interfaces.
  • 79. ASP.NET AJAX  AJAX web applications also make use of all the current browsers’ ability to asynchronously request and receive information from the browser independently of the usual page request/page receive/page display cycle.  Thisability to asynchronously communicate with the server makes it possible to create pages that are more responsive and l di i d less disruptive. ti
  • 80. Normal web application client-server interaction
  • 81. AJAX web application client-server interaction
  • 82. ASP.NET AJAX Examples p Here client-side only (no communication with server) Javascript is being used to ih )J i i b i d provide a richer user experience. Here the browser is communicating asynchronously with the server (the loading animation tells the user this) in order to provide a list of relevant search terms. Javascript is being used to make the request and receive the d h data b k in either XML or JSON format. back h f
  • 83. AJAX  Asynchronous communication is typically achieved in y yp y Javascript using the XMLHttpRequest object (though some sites use hidden IFrame elements instead).  This bj t Thi object was initially offered i I t i iti ll ff d in Internet E l t Explorer 5 as an ActiveX component;  FireFox, Opera, and Safari subsequently have added native support for XMLHttpRequest.  However, since Internet Explorer 5 and 6 XMLHttpRequest support is via an ActiveX component, it is possible for the pp p , p user to disable it via browser settings.  Internet Explorer 7, like the other browsers now supports XMLHttpRequest natively natively.
  • 84. AJAX  While richer AJAX web applications are a real boon for the user, creating them can be a real nightmare for the developer. g p  Javascript as a language lacks the kind of object- oriented features developers expect.  As well, Javascript can be quite difficult to debug.  As a consequence, there has been a proliferation of frameworks and toolkits to simplify the process of f k d lk lf h f developing AJAX applications.
  • 85. Why AJAX Applications Are Good y pp  Fewer roundtrips  Less bandwidth  only need to transfer info/markup that needs updating  Less work for the web server  More responsive for the user
  • 86. Why AJAX Applications Are Bad y pp  Accessibility problems  Often don’t work very well with screen readers.  Can be harder to develop  Can be a nightmare to debug
  • 87. AJAX at Work 87 Only these areas were “updated” creating the illusion of better 1 responsiveness 2 Notice: no obvious round-trip (though request + execution + response did happen, it just happened p pp , j pp in the background asynchronously).
  • 88. ASP.NET AJAX Coding g 88 <form id="form1" runat="server"> Ensures appropriate Javascript libraries are sent <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> to browser. <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> Any postback requests within <fieldset> this UpdatePanel will be done <legend>Sample Form ‐ Testing Autopostback</legend> asynchronously. y y <p><label>Address: </label><br />  <asp:TextBox ID="txtAddress" runat="server" /></p> <p><label>Country: </label><br /> <asp:DropDownList ID="drpCountry" runat="server" AutoPostBack="true" onselectedindexchanged="drpCountry_SelectedIndexChanged"> <asp:ListItem>United States</asp:ListItem> p p <asp:ListItem>Canada</asp:ListItem> </asp:DropDownList></p> <p><label><asp:Literal ID="litZipOrPostal" runat="server" Text="Zip: " /></label> <br /> <asp:TextBox ID="txtZipOrPostal" runat="server" /></p> <asp:Button ID="btnSubmit" runat="server" Text="Submit"  onclick="btnSubmit_Click" /> </fieldset> /fi ld t <asp:Label ID="labMessage" runat="server" /> </ContentTemplate> </asp:UpdatePanel> </form>
  • 89. 89 ASP.NET B hi d h S ASPNET Behind the Scenes Warning: Advanced Stuff Ahead W i Ad d S ff Ah d (you may want to wait until later to cover this)
  • 90. ASP.NET Behind the Scenes 90  What happens when the browser requests an pp q ASP.NET web page?  Quick Answer  the visual elements of the page are parsed into a class,  this class, along with its code is dynamically compiled (into MSIL) (i t MSIL),  This MSIL is JIT compiled and then executed on the server, ,  Execution produces the HTML and Javascript that is then sent to the browser.
  • 91. ASP.NET 2.0 Compilation Process p 91
  • 92. Where is this stuff? 92  The path for the generated class files created from the web forms along with the temporary assemblies is  [.NET System Directory]Temporary ASP.NET Files[virtual  directory][x][y]  where x and y are randomly-generated names.  For instance, the path for the assembly on my development server was C:WINDOWSMicrosoft.NETFrameworkv4.0.30319Temporary ASP.NET Fileschapter27229f9fd8d0746a9.
  • 93. Parsed Class (created by ASP.NET from web form) 93
  • 94. Page class g 94  All Web forms ultimately inherit from the Page class, which is defined in the System.Web.UI namespace.
  • 95. ASP.NET 2.0 Class Inheritance 95
  • 96. Page class g 96  The Page class inherits from the TemplateControl class, which in turn inherits from the Control class.  As a result, the Page class provides a great deal of functionality exposed as properties and methods that you can make use of in your web forms. y y  Some of these properties are analogous to the intrinsic global objects of ASP classic, such as Request, Response, Session, and Server.
  • 97. Application Lifecycle pp y 97  The page life cycle is just one of several processing steps which occur as part of the larger ASP.NET life cycle. y