CHAPTER 38 Using Server-Side ASP.NET AJAX The Ajax Vision ASP.NET is a server-side technology for building web applications.. For these reasons, Microsoft has both a server-side Ajax fra
Trang 1CHAPTER 38 Using Server-Side ASP.NET AJAX
The Ajax Vision
ASP.NET is a server-side technology for building web applications Almost all the work
happens on the web server and not the web browser Whenever you perform an action in
an ASP.NET page—such as clicking a button or sorting a GridView—the entire page must
be posted back to the web server Any significant action on a page results in a postback
If you think about it, this is incredibly inefficient When you perform a postback in an
ASP.NET page, the entire page must be transported across the Internet from browser to
server Next, the NET class that corresponds to the page must re-render the entire page
again from scratch Finally, the finished page must be sent back across the Internet to the
browser This whole long, slow, agonizing process must occur even if you are updating a
tiny section of the page
Using a server-side technology such as ASP.NET results in a bad user experience Every
time a user performs some action on a page, the universe temporarily freezes Whenever
you perform a postback, the browser locks, the page jumps, and the users must wait
patiently twiddling their thumbs while the page is reconstructed All of us have grown
accustomed to this awful user experience; however, we would never design our desktop
applications in the same way
When the members of the ASP.NET team invented ASP.NET in the late 1990s, there was
good reason to embrace the server side Getting a page that was written in JavaScript to
work consistently across different browsers, and even across different versions of the same
browser, was difficult The server side was safe and reliable
However, we’ve reached a tipping point Web developers are discovering that if they want
to build truly great applications, they need to leave the safety of the server side and enter
the wilds of the client side Today’s popular web applications such as Facebook, Google
Gmail, and YouTube all rely heavily on Ajax-based functionality
An Ajax application is a client-side web application written using native browser
technolo-gies such JavaScript and the DOM A pure Ajax application is a web application that
consists of a single page and performs all its communications with the web server through
web service calls
NOTE
Applications that use client-side technologies such as Flash, Flex, Java applets, and
Silverlight don’t count as Ajax applications because these are proprietary technologies
An Ajax application must use native browser technologies
Unlike a server-side web application, an Ajax application can be responsive to user
interac-tion If a user clicks a button in a server-side web application, the button Click event
doesn’t actually happen until the page gets posted back to the server In a server-side
application, the button Click event gets shifted in time and space In a client-side Ajax
Trang 2application, on the other hand, the button Click event happens when it happens: right
on the browser
In an Ajax application, the user interface layer is located in the browser (where it should
be) The business logic and data access layers are located on the server The user interface
layer accesses the business logic layer through web services
Server-Side Ajax Versus Client-Side Ajax
Microsoft has a complicated relationship with Ajax On the one hand, the company wants
to provide its existing ASP.NET developers with an easy way to implement Ajax
function-ality without having to learn JavaScript On the other hand, Microsoft recognizes that the
client is a powerful area to enable developers Therefore, it wants to provide web
develop-ers with the tools they need to build pure client-side Ajax applications For these reasons,
Microsoft has both a server-side Ajax framework and a client-side Ajax framework
If you want to retrofit an existing ASP.NET application to take advantage of Ajax, you can
take advantage of Microsoft’s side AJAX framework To take advantage of the
server-side framework, you don’t need to write a single line of JavaScript code You can continue
to build ASP.NET pages with server-side controls in the standard way You learn how to
take advantage of the server-side AJAX framework in this chapter
The advantage of the server-side framework is that it provides existing ASP.NET developers
with a painless method of doing Ajax The disadvantage of the server-side framework is
that it doesn’t escape all the problems associated with a server-side framework You still
have to run back to the server whenever you perform any client-side action
The Microsoft client-side AJAX framework (which we discuss in Chapter 40, “Client-Side
AJAX with jQuery”) embraces the client side When building applications with the
Microsoft client-side AJAX framework, you must build the application by using JavaScript
The advantage of building applications with the client-side framework is that you can
build rich and responsive web applications You can build web applications with the same
rich interactivity as a desktop application
Debugging Ajax Applications
Before we start discussing the Microsoft AJAX frameworks, you need to be aware of two
crucial debugging tools Debugging Ajax applications presents challenges not present in a
normal server-side application If an Ajax call fails, you won’t necessarily know You need
a way of monitoring the Ajax calls that happen between the browser and server
The first tool is Fiddler You can download this tool (for free) at http://www.fiddlertool
com Fiddler enables you to view HTTP requests and responses, including Ajax calls
Fiddler works by installing itself as a proxy between your web browser and the rest of the
universe You can use Fiddler with Internet Explorer, Mozilla Firefox, Opera, Safari, and
just about any other browser
Trang 3CHAPTER 38 Using Server-Side ASP.NET AJAX
After you install Fiddler, from Microsoft Internet Explorer, you can launch the tool by
selecting Tools, Fiddler2 After Fiddler launches, every browser request and response is
recorded in the Fiddler Web Sessions pane You can click a request and then click the
Session Inspector tab to see the full request and response (see Figure 38.1)
NOTE
If you can’t get Fiddler to capture page requests from localhost, try adding a period
directly after localhost in the browser address bar For example, make a request that
looks like this:
http://localhost.:6916/Original/Feedback.aspx
The other critical Ajax debugging tool is Firebug, which is a free Firefox extension You
can download Firebug by launching Firefox and selecting Tools, Add-ons Next, click the
Get Extensions link Finally, enter Firebug into the search box and follow the installation
instructions
Firebug, like Fiddler, enables you to monitor Ajax calls, but it enables you to do much
more After you install Firebug, you can click the bug icon at the bottom right of the
Firefox browser to open Firebug (see Figure 38.2)
FIGURE 38.1 Using Fiddler to inspect an Ajax request and response
Trang 4Firebug has several useful features for debugging JavaScript applications For example, it
enables you to set breakpoints in JavaScript scripts, inspect DOM elements, and determine
which CSS rules apply to which elements in a page Right now, however, I want you to
notice that you can use Firebug to monitor Ajax requests and responses If you click the
Net tab and the XHR tab, every Ajax call appears in the Firebug window You can click a
particular Ajax request to see the full request and response interaction between browser
and server
Using the UpdatePanel Control
Microsoft’s server-side AJAX framework consists of one main control: UpdatePanel The
UpdatePanel control enables you to update a portion of a page without updating the
entire page In other words, it enables you to perform partial-page rendering
Let’s start with a super-simple example of a page that uses the UpdatePanel control The
page in Listing 38.1 contains a ScriptManager control and an UpdatePanel control The
UpdatePanel control contains a single Button control When you click the button, only
the content contained in the UpdatePanel control is refreshed (see Figure 38.3)
FIGURE 38.2 Using Firebug in Mozilla Firefox
Trang 5CHAPTER 38 Using Server-Side ASP.NET AJAX
LISTING 38.1 UpdatePanelSimple.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>UpdatePanel Simple</title>
</head>
<body>
<form id=”form1” runat=”server”>
<asp:ScriptManager ID=”ScriptManager1” runat=”server” />
Page Time: <%= DateTime.Now.ToString(“T”) %>
<br /><br />
<asp:UpdatePanel
id=”up1”
runat=”server”>
<ContentTemplate>
UpdatePanel Time: <%= DateTime.Now.ToString(“T”) %>
<br />
<asp:Button
id=”btn”
Text=”Update”
runat=”server” />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
FIGURE 38.3 Using the UpdatePanel control
Trang 6The page in Listing 38.1 displays the current time both inside and outside the
UpdatePanel control When you click the button, only the time within the UpdatePanel
control is refreshed
Let’s look at a more realistic example that just begs for some Ajax (see Figure 38.4) The
page in Listing 38.2 does not use any of the ASP.NET AJAX controls It contains two
cascading DropDownList controls The first DropDownList enables you to pick a state, and
the second DropDownList enables you to pick a city The list of cities changes depending
on the state selected
LISTING 38.2 CascadingDropDownsNoAjax.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Cascading DropDownList Controls</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:Label
id=”lblState”
Text=”State:”
AssociatedControlID=”ddlState”
Runat=”server” />
<asp:DropDownList
id=”ddlState”
DataSourceID=”srcState”
DataTextField=”State”
DataValueField=”State”
FIGURE 38.4 A page with cascading DropDownList controls
Trang 7CHAPTER 38 Using Server-Side ASP.NET AJAX
AutoPostBack=”true”
Runat=”server” />
<asp:SqlDataSource
id=”srcState”
ConnectionString=’<%$ ConnectionStrings:con %>’
SelectCommand=”SELECT State FROM State
ORDER BY State”
Runat=”server” />
<br /><br />
<asp:Label
id=”Label1”
Text=”City:”
AssociatedControlID=”ddlCity”
Runat=”server” />
<asp:DropDownList
id=”ddlCity”
DataSourceID=”srcCity”
DataTextField=”City”
AutoPostBack=”true”
Runat=”server” />
<asp:SqlDataSource
id=”srcCity”
ConnectionString=’<%$ ConnectionStrings:con %>’
SelectCommand=”SELECT City FROM City
WHERE State=@State
ORDER BY City”
Runat=”server”>
<SelectParameters>
<asp:ControlParameter Name=”State” ControlID=”ddlState” />
</SelectParameters>
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
When you select a state using the first DropDownList control, there is a click, and the page
posts back to itself to populate the second DropDownList control with matching cities
Clearly, the user experience here is less than optimal All work must stop while the page
performs a postback
Trang 8Let’s fix up this page with some Ajax The page in Listing 38.3 is exactly the same as the
page in Listing 38.2, except for two changes First, the page now contains a ScriptManager
control Second, and more important, the DropDownList controls in Listing 38.3 are
wrapped inside an UpdatePanel control
LISTING 38.3 CascadingDropDownsAjax.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head id=”Head1” runat=”server”>
<title>Cascading DropDownList Controls</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:ScriptManager
id=”sm1”
Runat=”server” />
<asp:UpdatePanel
id=”UpdatePanel1”
Runat=”server”>
<ContentTemplate>
<asp:Label
id=”lblState”
Text=”State:”
AssociatedControlID=”ddlState”
Runat=”server” />
<asp:DropDownList
id=”ddlState”
DataSourceID=”srcState”
DataTextField=”State”
DataValueField=”State”
AutoPostBack=”true”
Runat=”server” />
<asp:SqlDataSource
id=”srcState”
ConnectionString=’<%$ ConnectionStrings:con %>’
SelectCommand=”SELECT State FROM State
ORDER BY State”
Runat=”server” />
Trang 9CHAPTER 38 Using Server-Side ASP.NET AJAX
<br /><br />
<asp:Label
id=”Label1”
Text=”City:”
AssociatedControlID=”ddlCity”
Runat=”server” />
<asp:DropDownList
id=”ddlCity”
DataSourceID=”srcCity”
DataTextField=”City”
AutoPostBack=”true”
Runat=”server” />
<asp:SqlDataSource
id=”srcCity”
ConnectionString=’<%$ ConnectionStrings:con %>’
SelectCommand=”SELECT City FROM City
WHERE State=@State
ORDER BY City”
Runat=”server”>
<SelectParameters>
<asp:ControlParameter Name=”State” ControlID=”ddlState” />
</SelectParameters>
</asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
In Listing 38.3, when you select a new state with the first DropDownList control, matching
cities display in the second DropDownList control However, there is no click and there is
no noticeable postback The browser doesn’t freeze, and the page does not jump
Everything happens smoothly and professionally through the magic of Ajax
The ScriptManager control in Listing 38.3 adds the necessary JavaScript scripts to enable
Ajax Anytime you create a page that uses Ajax, regardless of whether you are doing
server-side or client-side Ajax, you’ll add a ScriptManager control to the page
The UpdatePanel control is the control that is doing all the Ajax work here It hijacks the
normal postback that would happen when you select a new item in the first DropDownList
Trang 10control The UpdatePanel hijacks the normal postback and performs a “sneaky” postback
to grab the new content in the background
Let’s look at another page that takes advantage of the UpdatePanel control The page in
Listing 38.4 represents a simple customer feedback form (see Figure 38.5) The page
contains a FormView control and a GridView control The FormView control renders the
insert form, and the GridView control is used to display previous customer responses You
can sort the contents of GridView in order of the different columns
FIGURE 38.5 Entering customer feedback into an Ajax-enabled form
LISTING 38.4 Feedback.aspx
<%@ Page Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Feedback</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div>
<asp:ScriptManager
id=”sm1”
Runat=”server” />