web ii - 02 - how asp.net works

98
HOW ASP.NET WORKS 2

Upload: randy-connolly

Post on 01-Dec-2014

10.673 views

Category:

Technology


3 download

DESCRIPTION

Lecture slides for COMP 3512 (Web 2: Server-Side Development). Suitable for Web 2 course in a degree following CIT/CIS/CS ACM model curriculum.

TRANSCRIPT

Page 1: Web II - 02 - How ASP.NET Works

HOW ASP.NET WORKS

2

Page 2: Web II - 02 - How ASP.NET Works

Overview2

ASP.NET Event Model ASP.NET Event Model ASP.NET Code Compilation The P  Class The Page Class ASP.NET Application Lifecycle

Page 3: Web II - 02 - How ASP.NET Works

Event Model3

One of the key features of ASP.NET is that it uses an 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. clicks a button or selects an item from a list.

When an event is raised, the handler for that specific event is executed.

Page 4: Web II - 02 - How ASP.NET Works

Event Handlers4

In the .NET Framework, all event handlers have a 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

( b l f h d (or a subclass of EventArgs, such as CommandEventArgs or ImageClickEventArgs).

protected void Page Load(object sender, EventArgs e)protected void Page_Load(object sender, EventArgs e){

…}

Page 5: Web II - 02 - How ASP.NET Works

ASP.NET Event Systemy5

The event system in ASP.NET operates in a different 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 i h dli i d i h Since its event handling requires a round-trip to the server, ASP.NET offers a smaller set of events in comparison to a totally client-based event system.

Page 6: Web II - 02 - How ASP.NET Works

ASP.NET Event Systemy6

Page 7: Web II - 02 - How ASP.NET Works

HTTP P l

A Di i

HTTP Protocol7

A Digression

Page 8: Web II - 02 - How ASP.NET Works

HTTP8

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

Page 9: Web II - 02 - How ASP.NET Works

HTTP9

An HTTP session is a sequence of network request-q qresponse transactions. An HTTP client initiates a request. It establishes a Transmission Control Protocol (TCP) connection

to a particular port on a host (typically port 80) An HTTP server listening on that port waits for a client's se ve s e g o a po wa s o a c e s

request message. Upon receiving the request, the server sends back

a status line such as "HTTP/1 1 200 OK" and a status line, such as HTTP/1.1 200 OK , and a message of its own, the body of which is perhaps the

requested resource, an error message, or some other information.

Page 10: Web II - 02 - How ASP.NET Works

HTTP Requestsq

An HTML page, once received, typically will invoke

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  />

Page 11: Web II - 02 - How ASP.NET Works

HTTP E l 1HTTP Example 1

Page 12: Web II - 02 - How ASP.NET Works

1. User makes requestq

Page 13: Web II - 02 - How ASP.NET Works

2. Browser sends HTTP request to server

GET /comp1274/randyc/lab10done/enter_country.htm HTTP/1.1Request Line

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; Request Header 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 lineBlank line

Browser Web Server

HTTP Request

owse Web Se ve

Page 14: Web II - 02 - How ASP.NET Works

3. Server receives and processes the HTTP request

Browser Web Server

HTTP Request

Browser Web Server

Retrieve Requested file

Page 15: Web II - 02 - How ASP.NET Works

4. Server sends HTTP response backp

HTTP/1.1 200 OKResponse Line + Status Code

Server: Microsoft‐IIS/5.0

Date: Thu, 30 Mar 2006 19:50:54 GMT

Content‐Type: text/html

Accept‐Ranges: bytesResponse Header

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:  Servery

<input type="text" name="search"><p>

<input type="submit">

</form>

Server

HTTP Response

Response Content

</body></html>

Browser

Page 16: Web II - 02 - How ASP.NET Works

5. Browser displays responsep y p

Page 17: Web II - 02 - How ASP.NET Works

6. User submits data

Page 18: Web II - 02 - How ASP.NET Works

7. Browser sends HTTP request to server

POST /comp1274/randyc/lab10done/form_filter.asp HTTP/1.1

A t  */*Accept: */*

Referer: http://csweb2.mtroyal.ca/comp1274/randyc/lab10done/enter_country.htm

Accept‐Language: en‐us,en‐ca;q=0.5

C t t T   li ti / f l d dContent‐Type: application/x‐www‐form‐urlencoded

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)

Page 19: Web II - 02 - How ASP.NET Works

What if method=get rather than post?

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

GET /comp1274/randyc/lab10done/form_filter.asp?Search=Canada HTTP/1.1

Then the user entered form data is added to the requested URL

Versus

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

Then the user entered form data is added to the end of HTTP request headerPOST /comp1274/randyc/lab10done/form_filter.asp HTTP/1.1

rest of HTTP request header goes here

Search=Canada

Page 20: Web II - 02 - How ASP.NET Works

8. Server receives and processes the HTTP request

Browser Web Server

HTTP Request

Browser Web Server

Server processeshthe request

Page 21: Web II - 02 - How ASP.NET Works

9. Server script generates response sent back to browserbrowser

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>

/b d /ht l</body></html>

Page 22: Web II - 02 - How ASP.NET Works

10. Browser displays the responsep y p

Page 23: Web II - 02 - How ASP.NET Works

HTTP E l 2HTTP Example 2

Page 24: Web II - 02 - How ASP.NET Works

1. User makes requestq

Page 25: Web II - 02 - How ASP.NET Works

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

Page 26: Web II - 02 - How ASP.NET Works

3. Server receives and processes the HTTP request

Browser Web Server

HTTP Request

Browser Web Server

Server processeshthe request

Page 27: Web II - 02 - How ASP.NET Works

4. Server script generates response sent back to browser

HTTP/1.1 200 OK

S  Mi ft IIS/5 0Server: Microsoft‐IIS/5.0

Date: Thu, 30 Mar 2006 19:51:06 GMT

Content‐Length: 1590

Content‐Type: text/htmlContent 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>      <td><b>Run Time</b></td>      

</tr>

...

Page 28: Web II - 02 - How ASP.NET Works

5. Browser displays the responsep y p

Page 29: Web II - 02 - How ASP.NET Works

6. User makes request (click on a link)q ( )

Page 30: Web II - 02 - How ASP.NET Works

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.cay

Connection: Keep‐Alive

Page 31: Web II - 02 - How ASP.NET Works

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

/h lContent‐Type: text/html

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>

...

Page 32: Web II - 02 - How ASP.NET Works

9. Browser displays the responsep y p

Page 33: Web II - 02 - How ASP.NET Works

HTTP E l 3HTTP Example 3

Page 34: Web II - 02 - How ASP.NET Works

1. User makes requestq

Page 35: Web II - 02 - How ASP.NET Works

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

Page 36: Web II - 02 - How ASP.NET Works

3. Server receives and processes the HTTP request

Browser Web Server

HTTP Request

Browser Web Server

Server processesthe request

Page 37: Web II - 02 - How ASP.NET Works

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

HTTP/1.1 404 Object Not Found

i f /Server: Microsoft‐IIS/5.0

Date: Thu, 30 Mar 2006 19:51:06 GMT

Content‐Length: 4040

Content‐Type: text/htmlContent 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 

...

Page 38: Web II - 02 - How ASP.NET Works

5. Browser displays the responsep y p

Page 39: Web II - 02 - How ASP.NET Works

Examining HTTP g39

Google Chrome

FireFox Firebug Extension

Page 40: Web II - 02 - How ASP.NET Works

B k ASPNET

Di i

Back to ASP.NET40

Digression over …

Page 41: Web II - 02 - How ASP.NET Works

ASP.NET Event Handlingg41

How then does ASP.NET communicate the triggering 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

Page 42: Web II - 02 - How ASP.NET Works

Postback42

Postback is the process by which the browser posts Postback is the process by which the browser posts information back to itself. That is, posts information back to the server by , p y

requesting the same page. That is, it is simply a HTTP POST request for the same

ASP.NET page

Page 43: Web II - 02 - How ASP.NET Works

Postback43

<body><form id="form1" runat="server">

EventTest.aspx (on 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" value="/wEPDwUJMzU4OTQyMTQyD2QWAgIDD2Q …

Result in browser

Q: Which page will be …<input type="submit" name="btnEnter" value="Submit" id="btnEnter" /><p><span id="msg1">In Page_Load<br/></span></p>…

requested when the user presses the submit button?

Page 44: Web II - 02 - How ASP.NET Works

Postback44

Postback in ASP.NET 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 yposted back to the server, and then redisplayed again, is sometimes also called a postback round trip.

Page 45: Web II - 02 - How ASP.NET Works

Postback45

In other words, it is postback which makes it possible 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.

Page 46: Web II - 02 - How ASP.NET Works

Postback46

Page 47: Web II - 02 - How ASP.NET Works

Event Typesyp47

Two types Two types Page events Always triggered and always in a certain specific order (see y gg y p (

Page Lifecycle). Triggered and handled on the server.

Th tb k i l d Thus no postback involved

Control events Associated with particular controls and only triggered in Associated with particular controls and only triggered in

certain circumstances. Requires postback

Page 48: Web II - 02 - How ASP.NET Works

Postback and Events48

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

Page 49: Web II - 02 - How ASP.NET Works

HTTP + Postback49

GET http://localhost:53372/Chapter2/EventTest.aspx First request for page (from URL, or link, bookmark, …) 1NOTE: since this is the first request, there are no querystring parameters in the request

1

HTTP/1.1 200 OKServer: ASP.NET Development Server/9.0.0.0Date: Tue, 21 Sep 2010 18:52:36 GMTC t t th 2039

2 Page executes on the server.

Content‐Length: 2039Content‐Type: text/html

<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Event Test</title></head><body><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

Page 50: Web II - 02 - How ASP.NET Works

HTTP + Postback50

GET http://localhost:53372/Chapter2/EventTest.aspx3 …

Name=Randy&myList=Melvillee&__VIEWSTATE=/wEPDwUJMzU4…

Second request for page (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)

3

4 HTTP/1.1 200 OKServer: ASP.NET Development Server/9.0.0.0Date: Tue  21 Sep 2010 18:52:36 GMT

one of which is the viewstate (as well as user s form data)

Date: Tue, 21 Sep 2010 18:52:36 GMTContent‐Length: 2039Content‐Type: text/html

<html xmlns="http://www.w3.org/1999/xhtml"><head><title>Event Test</title></head>

Server can figure out that this isa postback request from the presence of the iewstate<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 …...

presence of the viewstatequerystring parameter

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

Page 51: Web II - 02 - How ASP.NET Works

View State51

View state is one of the most important features of View state is one of the most important features of ASP.NET.

It is a specially encoded string that is used to retain 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 "/wEPDwUJODExMDE5NzY5D2QWAgIDD2QWAgIBDw8WAh4EVGV4dAUKMDgvMDEvalue= /wEPDwUJODExMDE5NzY5D2QWAgIDD2QWAgIBDw8WAh4EVGV4dAUKMDgvMDEvMjAwNmRkZDZPhFHJER4chf3nmlgfL+uq4W58" />

Page 52: Web II - 02 - How ASP.NET Works

View State52

View state is a mechanism for preserving display View state is a mechanism for preserving display state within web forms.

Recall that HTTP is by nature stateless. 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.

Page 53: Web II - 02 - How ASP.NET Works

View State53

View state is generated once all the page code has 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 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-pvalue 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".

Page 54: Web II - 02 - How ASP.NET Works

View State54

When the form is posted back, ASP.NET receives the 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.

Page 55: Web II - 02 - How ASP.NET Works

View State55

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

Page 56: Web II - 02 - How ASP.NET Works

Viewstate

However, sometimes a developer may wish to turn

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

d l d d d h to download and render the page.

Page 57: Web II - 02 - How ASP.NET Works

Large View Stateg57

Viewstate = 277K

Page 58: Web II - 02 - How ASP.NET Works

Turn Off Viewstate

If a page is not going to post back to itself, you can

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

You can also disable viewstate on a control-by-

<%@ Page ... EnableViewState="false" %>

You can also disable viewstate on a control bycontrol basis. <asp:Label runat="server" ID="Label2" ViewStateMode="Disabled" ... />

Page 59: Web II - 02 - How ASP.NET Works

Disabling Viewstateg59

viewstate = 0.05 K

Page 60: Web II - 02 - How ASP.NET Works

Disabling Viewstateg

Do remember that viewstate is required for any

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 Again, you only want to disable it for pages or controls that don’t need it.

Page 61: Web II - 02 - How ASP.NET Works

Page Life Cycleg y61

Page and control events occur in a certain order Page and control events occur in a certain order which we can call the page life cycle.

Five general stages: Five general stages: Page initialization Loading Loading Postback control event handling Rendering g Unloading

Page 62: Web II - 02 - How ASP.NET Works

Complete Page Life Cyclep g y62

Page 63: Web II - 02 - How ASP.NET Works

Event Handlers63

Within each of these stages, the ASP.NET page 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 For most situations, you only need to worry about the Page_Load event and certain control events.

Page 64: Web II - 02 - How ASP.NET Works

Event Handlers64

Because page events always happen, you simply need to p g y pp , y p ydefine a page event handler by using the appropriate naming convention: Page XXXX where XXXX is the event name 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:Button id="btnSubmit" runat="server" 

or programmatically in the code (rare).

<asp: utto d bt Sub t u at se eOnClick="btnSubmit_Click" />

btnSubmit.Click += new EventHandler( this.btnSubmit_Click );

Page 65: Web II - 02 - How ASP.NET Works

Adding Event Handlers in VSg65

Page 66: Web II - 02 - How ASP.NET Works

Detecting Postbackg66

There are times when you may want your page to 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.

Page 67: Web II - 02 - How ASP.NET Works

Detecting Postbackg67

Your page can test if it is being requested for the Your page can test if it is being requested for the first time via the IsPostBack property This property is equal to false if the page is being p p y 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}…

}

Page 68: Web II - 02 - How ASP.NET Works

Postback and Non-Postback Controls68

Button-type controls with Click events always generate an immediate postback to the server.

But not all control events generate an immediate postback. postback.

In fact, most control events by default do not cause a postback.

S l f i l Some controls—for instance, a Label control—never can cause a postback.

Change events also do not generate a postback, by d f lt default. An example of a change event is selecting an item from a drop-

down list or entering text into a text box.

Page 69: Web II - 02 - How ASP.NET Works

Change Eventsg69

You may be able to enable postback for change- You may be able to enable postback for changetype events by setting the control’s AutoPostBackproperty to true. p p y 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 handler for the SelectedIndexChanged event.

Page 70: Web II - 02 - How ASP.NET Works

Without AutoPostBack70

Notice: label didn’t changeNotice: label didn t change

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

Page 71: Web II - 02 - How ASP.NET Works

With AutoPostBack71

Notice: label changed because list selection triggered a postback

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

Page 72: Web II - 02 - How ASP.NET Works

AutoPostBack72

<fieldset><legend>Sample Form ‐ Testing Autopostback</legend><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" <asp:Button ID="btnSubmit" runat="server" Text="Submit" 

onclick="btnSubmit_Click" /></fieldset><asp:Label ID="labMessage" runat="server" />

protected void Page_Load(object o, EventArgs e){

labMessage.Text = "In page load<br/>";}

t t d  id d C t S l t dI d Ch d( bj t   E tA )protected void drpCountry_SelectedIndexChanged(object o, EventArgs e){

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";litZipOrPostal.Text   Zipcode ;}protected void btnSubmit_Click(object sender, EventArgs e){

labMessage.Text += "In button event handler<br/>";}

Page 73: Web II - 02 - How ASP.NET Works

Visually Detecting Postbacky g73

1

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

3When testing a web site locally, this can happen too quickly to notice, but will be noticeable when hosted on a real remote web server (especially a busy one).

Postback request finished rendering in browser.

Page 74: Web II - 02 - How ASP.NET Works

Visually Detecting Postbacky g74

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

Page 75: Web II - 02 - How ASP.NET Works

Using AJAX g

It is possible to asynchronously make a postback

75

It is possible to asynchronously make a postbackrequest using ASP.NET’s AJAX abilities. This avoids the blank screen and wait of a full postbackp

request. Instead, the browser will make the request “in the

background”using asynchronous Javascript (AJAX).

Page 76: Web II - 02 - How ASP.NET Works

ASPNET AJAX

A h Di i

ASP.NET AJAX76

Another Digression

Page 77: Web II - 02 - How ASP.NET Works

ASP.NET AJAX

ASP.NET AJAX adds Asynchronous JavaScript and ASP.NET AJAX adds Asynchronous JavaScript and XML (AJAX) support to ASP.NET.

ASP.NET AJAX was up until the fall of 2006 was ASP.NET AJAX was up until the fall of 2006 was known by the code-known of Atlas.

Page 78: Web II - 02 - How ASP.NET Works

ASP.NET AJAX

AJAX is not a product. AJAX is not a product. Rather it is the most common name given to a style of

web development that makes fuller use of Javascriptand the browser Document Object Model (DOM) in the construction of web application user interfaces.

Page 79: Web II - 02 - How ASP.NET Works

ASP.NET AJAX

AJAX web applications also make use of all the 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. This ability to asynchronously communicate with the

server makes it possible to create pages that are more i d l di ti responsive and less disruptive.

Page 80: Web II - 02 - How ASP.NET Works

Normal web application client-server interaction

Page 81: Web II - 02 - How ASP.NET Works

AJAX web application client-server interaction

Page 82: Web II - 02 - How ASP.NET Works

ASP.NET AJAX Examplesp

Here client-side only (no communication i h ) J i i b i d with server) Javascript is being used to

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 h d b k h XML JSON freceive the data back in either XML or JSON format.

Page 83: Web II - 02 - How ASP.NET Works

AJAX

Asynchronous communication is typically achieved in y yp yJavascript using the XMLHttpRequest object (though some sites use hidden IFrame elements instead). Thi bj t i iti ll ff d i I t t E l 5 This object was initially offered in Internet 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 , puser to disable it via browser settings.

Internet Explorer 7, like the other browsers now supports XMLHttpRequest nativelyXMLHttpRequest natively.

Page 84: Web II - 02 - How ASP.NET Works

AJAX

While richer AJAX web applications are a real 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

f k d lk l f h f frameworks and toolkits to simplify the process of developing AJAX applications.

Page 85: Web II - 02 - How ASP.NET Works

Why AJAX Applications Are Goody pp

Fewer roundtrips Fewer roundtrips Less bandwidth

only need to transfer info/markup that needs updating only need to transfer info/markup that needs updating

Less work for the web server More responsive for the user More responsive for the user

Page 86: Web II - 02 - How ASP.NET Works

Why AJAX Applications Are Bady pp

Accessibility problems Accessibility problems Often don’t work very well with screen readers.

Can be harder to develop Can be harder to develop Can be a nightmare to debug

Page 87: Web II - 02 - How ASP.NET Works

AJAX at Work87

1

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

2 Notice: no obvious round-trip (though request + execution + response did happen, it just happened p pp , j ppin the background asynchronously).

Page 88: Web II - 02 - How ASP.NET Works

ASP.NET AJAX Codingg88

<form id="form1" runat="server"> Ensures appropriate Javascript libraries are sent

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server"><ContentTemplate>

<fieldset><legend>Sample Form ‐ Testing Autopostback</legend>

Javascript libraries are sent to browser.

Any postback requests within this UpdatePanel will be done asynchronously.

<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>

y y

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" />/fi ld t</fieldset>

<asp:Label ID="labMessage" runat="server" /></ContentTemplate>

</asp:UpdatePanel>

</form>

Page 89: Web II - 02 - How ASP.NET Works

ASPNET B hi d h S

W i Ad d S ff Ah d

ASP.NET Behind the Scenes89

Warning: Advanced Stuff Ahead (you may want to wait until later to cover this)

Page 90: Web II - 02 - How ASP.NET Works

ASP.NET Behind the Scenes90

What happens when the browser requests an pp qASP.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

(i t MSIL) (into 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.

Page 91: Web II - 02 - How ASP.NET Works

ASP.NET 2.0 Compilation Processp91

Page 92: Web II - 02 - How ASP.NET Works

Where is this stuff?92

The path for the generated class files created from 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:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\chapter2\7229f9fd\8d0746a9.

Page 93: Web II - 02 - How ASP.NET Works

Parsed Class (created by ASP.NET from web form)

93

Page 94: Web II - 02 - How ASP.NET Works

Page classg94

All Web forms ultimately inherit from the Page class, All Web forms ultimately inherit from the Page class, which is defined in the System.Web.UI namespace.

Page 95: Web II - 02 - How ASP.NET Works

ASP.NET 2.0 Class Inheritance95

Page 96: Web II - 02 - How ASP.NET Works

Page classg96

The Page class inherits from the TemplateControl class, 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 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.

Page 97: Web II - 02 - How ASP.NET Works

Application Lifecyclepp y97

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

Page 98: Web II - 02 - How ASP.NET Works

Application Lifecyclepp y98