2.2. ASP.NET AJAX Applications

The next step is to build a basic sample utilizing this new framework. First, create a new ASP.NET Web Site application using the New Web Site dialog. Name the project AjaxWebSite. You will notice (as shown here in Figure 2-3) that there is not a separate type of ASP.NET project for building an ASP.NET AJAX application because every ASP.NET application that you now build is AJAX-enabled.

After you create the application, you will be presented with what is now a standard Web site project. However, you may notice some additional settings in the web.config file that are new to ASP.NET 3.5. At the top of the web.config file, there are new configuration sections that are registered that deal with AJAX. This section of web.config is presented in Listing 2-1.

Figure 2-3. Figure 2-3

Example 2-1. The <configSections> element for an ASP.NET 3.5 application
<?xml version="1.0"?>

<configuration>
  <configSections>
     <sectionGroup name="system.web.extensions"
      type="System.Web.Configuration.SystemWebExtensionsSectionGroup,
        System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
        PublicKeyToken=31BF3856AD364E35">
        <sectionGroup name="scripting"
         type="System.Web.Configuration.ScriptingSectionGroup,
            System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
            PublicKeyToken=31BF3856AD364E35">
          <section name="scriptResourceHandler"
           type="System.Web.Configuration.ScriptingScriptResourceHandlerSection,
              System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
              PublicKeyToken=31BF3856AD364E35" requirePermission="false"
           allowDefinition="MachineToApplication"/>
            <sectionGroup name="webServices"
             type="System.Web.Configuration.ScriptingWebServicesSectionGroup,
             System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
               PublicKeyToken=31BF3856AD364E35">
               <section name="jsonSerialization"
                type="System.Web.Configuration.ScriptingJsonSerializationSection,
                   System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                   PublicKeyToken=31BF3856AD364E35" requirePermission="false"
                allowDefinition="Everywhere" />
               <section name="profileService"
                type="System.Web.Configuration.ScriptingProfileServiceSection,
                  System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                  PublicKeyToken=31BF3856AD364E35" requirePermission="false"
                allowDefinition="MachineToApplication" />
              <section name="authenticationService"
              type="System.Web.Configuration.ScriptingAuthenticationServiceSection,

System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                   PublicKeyToken=31BF3856AD364E35" requirePermission="false"
                 allowDefinition="MachineToApplication" />
               <section name="authenticationService"
               type="System.Web.Configuration.
                          ScriptingAuthenticationServiceSection,
                  System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                  PublicKeyToken=31BF3856AD364E35" requirePermission="false"
               allowDefinition="MachineToApplication" />
               <section name="roleService"
               type="System.Web.Configuration.ScriptingRoleServiceSection,
                  System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                  PublicKeyToken=31BF3856AD364E35" requirePermission="false"
               allowDefinition="MachineToApplication" />
            </sectionGroup>
         </sectionGroup>
      </sectionGroup>
   </configSections>

<! -- Configuration removed for clarity -- >

</configuration>

In addition to the <configSections> element now a part of the web.config, you will also find a new <system.webServer> section. This section is for ASP.NET AJAX applications that are running within the confines of IIS 7.0. This section of configuration code is presented here in Listing 2-2.

Example 2-2. The <system.webServer> section for AJAX and IIS 7.0
<system.webServer>
   <validation validateIntegratedModeConfiguration="false"/>
   <modules>
      <remove name="ScriptModule" />
      <add name="ScriptModule" preCondition="managedHandler"
          type="System.Web.Handlers.ScriptModule, System.Web.Extensions,
          Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   </modules>
   <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <remove name="ScriptHandlerFactory" />
      <remove name="ScriptHandlerFactoryAppServices" />
      <remove name="ScriptResource" />
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx"
       preCondition="integratedMode"
       type="System.Web.Script.Services.ScriptHandlerFactory,
             System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
             PublicKeyToken=31BF3856AD364E35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*"
       path="*_AppService.axd" preCondition="integratedMode"
       type="System.Web.Script.Services.ScriptHandlerFactory,

System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                    PublicKeyToken=31BF3856AD364E35"/>
            <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD"
                path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler,
                                  System.Web.Extensions, Version=3.5.0.0, Culture=neutral,
                                  PublicKeyToken=31BF3856AD364E35" />
   </handlers></system.webServer>

With these aspects of the web.config file in place (as provided by the ASP.NET Web Site project type), the next step is to build a simple ASP.NET page that does not yet make use of AJAX.

2.2.1. Building a Simple ASP.NET Page without AJAX

The first step is to build a simple page that does not yet make use of the AJAX capabilities offered by ASP.NET 3.5. Your page needs only a Label control and Button server control. The code for the page is presented in Listing 2-3.

Example 2-3. A simple ASP.NET 3.5 page that does not use AJAX
<%@ Page Language="C#" %>

<script runat="server">
       protected void Button1_Click(object sender, EventArgs e)
       {
          Label1.Text = DateTime.Now.ToString();
       }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>My Normal ASP.NET Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
           <asp:Label ID="Label1" runat="server"></asp:Label>
           <br />
           <br />
           <asp:Button ID="Button1" runat="server" Text="Click to get machine time"
                  onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

When you pull this page up in the browser, it contains only a single button. When the button is clicked, the Label control that is on the page is populated with the time from the server machine. Before the button is clicked, the page's code is similar to the code presented in Listing 2-4.

Example 2-4. The page output for a page that is not using AJAX
<!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><title>
 My Normal ASP.NET Page
</title></head>
<body>
    <form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
 value="/wEPDwULLTE4OTg4OTc0MjVkZIgwrMMmvqXJHfogxzgZ92wTUORS" />
</div>
    <div>
        <span id="Label1"></span>
        <br />
        <br />
        <input type="submit" name="Button1" value="Click to get machine time"
         id="Button1" />
    </div>
<div>

 <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
  value="/wEWAgLFpoapCAKM54rGBkhUDe2q/7eVsROfd9QCMK6CwiI7" />
</div></form>
</body>
</html>

There is not much in this code. There is a little ViewState and a typical form that will be posted back to the Default.aspx page. When the end user clicks the button on the page, a full post back to the server occurs and the entire page is reprocessed and returned to the client's browser. Really, the only change made to the page is that the <span id="Lable1"></span> element is populated with a value, but in this case, the entire page is returned. This return is presented here in Listing 2-5.

Example 2-5. The returned code from the button click event
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title>
 My Normal ASP.NET Page
</title></head>
<body>
    <form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
 value="/wEPDwUKLTE2MjY5MTY1NQ9kFgICAw9kFgICAQ8PFgIeBFRleHQFEzcvMy8yMDA
       4IDU6MzM6NDAgQU1kZGSDYMwC9k0QFgaZvlblIaJEWMQxIA==" />
</div>

    <div>
        <span id="Label1">7/3/2008 5:33:40 AM</span>

<br />
        <br />
        <input type="submit" name="Button1" value="Click to get machine time"

         id="Button1" />
    </div>

<div>

  <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
  value="/wEWAgLFsJKtCwKM54rGBmLn3/qARdTOYYDTaj6+5D8E4bEQ" />
</div></form>
</body>
</html>

From this, you can see that the entire page was returned back to the client. This process causes the entire page in the browser to disappear and reload (causing the flash). All this work and data moving across the wire only to deal with a small bit of content actually changing on the page.

Next, this chapter reviews building a simple ASP.NET page that makes use of the built-in ASP.NET AJAX capabilities.

2.2.2. Building a Simple ASP.NET Page Using AJAX

After seeing the first example on a simple page that didn't deal with AJAX in any manner, the next step is to build upon that page from Listing 2-3 and add the built-in AJAX capabilities to it. For this example, you will be adding some additional controls. Two of the controls to add are typical ASP.NET server controls — another Label and Button server control. In addition to these controls, you are going to have to add some ASP.NET AJAX controls.

One new thing you will find in the Visual Studio 2008 toolbox is a new section titled AJAX Extensions. This section includes the new AJAX focused controls that are provided as part of ASP.NET 3.5. This new section is shown in Figure 2-4.

Figure 2-4. Figure 2-4

From the AJAX Extensions group in the Visual Studio 2008 toolbox, add a ScriptManager server control to the top of your ASP.NET page and include the second Label and Button control inside an UpdatePanel control. The UpdatePanel control is a template server control; you can include any number of items within it (just as other templated ASP.NET server controls). When you have your page set up, the design view should look something like Figure 2-5.

Figure 2-5. Figure 2-5

When you have this all together on the design view of the ASP.NET page you are working with, the code for this page should be similar to what is presented in Listing 2-6.

Example 2-6. A simple ASP.NET AJAX page
<%@ Page Language="C#" %>

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Label2.Text = DateTime.Now.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

<title>My ASP.NET AJAX Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Click to get machine time"
            onclick="Button1_Click" />
        <br />
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
                <br />
                <br />
                <asp:Button ID="Button2" runat="server"
                 Text="Click to get machine time using AJAX"
                 onclick="Button2_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

When this page is pulled up in the browser, it has two buttons. The first button causes a complete page postback and updates the current time in the Label1 server control.

Clicking on the second button causes an AJAX asynchronous postback. Clicking this second button updates the current server time in the Label2 server control. When you click the AJAX button, the time in Label1 will not change at all, as it is outside of the UpdatePanel. A screenshot of the end result is presented in Figure 2-6.

Figure 2-6. Figure 2-6

Though you might think the code needed for the initial layout of the page will be quite similar (if not the same) as the example that didn't use AJAX, when you first pull up this page from Listing 2-6, the code of the page is actually quite different from the page that was built not using AJAX. Listing 2-7 shows the page results that you will see.

Example 2-7. The page output for a page that is using AJAX
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
My ASP.NET AJAX Page
</title></head>
<body>
    <form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
 value="/wEPDwULLTE4NzE5NTc5MzRkZDRIzHpPZg4GaO9Hox9A/RnOflkm" />
</div>

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
    theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>

<script src="/AJAXWebSite/WebResource.axd?d=o84znEj-
 n4cYi0Wg0pFXCg2&amp;t=633285028458684000" type="text/javascript"></script>

<script src="/AJAXWebSite/ScriptResource.axd?
 d=FETsh5584DXpx8XqIhEM50YSKyR2GkoMoAqraYEDU5_
 gi1SUmL2Gt7rQTRBAw56lSojJRQe0OjVI8SiYDjmpYmFP0
 CO8wBFGhtKKJwm2MeE1&amp;t=633285035850304000" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET AJAX client-side
  framework failed to load.'),
//]]>
</script>

<script src="/AJAXWebSite/ScriptResource.axd?
 d=FETsh5584DXpx8XqIhEM50YSKyR2GkoMoAqraYEDU5_

gi1SUmL2Gt7rQTRBAw56l7AYfmRViCoO2lZ3XwZ33TGiC
 t92e_UOqfrP30mdEYnJYs09ulU1xBLj8TjXOLR1k0&amp;t=633285035850304000"
 type="text/javascript"></script>
    <div>
        <script type="text/javascript">
//<![CDATA[
Sys.WebForms.PageRequestManager._initialize('ScriptManager1',
        document.getElementById('form1'));
Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1'],
         [], [], 90);
//]]>
</script>
        <span id="Label1"></span>
        <br />
        <br />
        <input type="submit" name="Button1" value="Click to get machine time"
         id="Button1" />
        <br />
        <br />
        <div id="UpdatePanel1">

                <span id="Label2"></span>
                <br />
                <br />
                <input type="submit" name="Button2" value="Click to get machine
                 time using AJAX" id="Button2" />
</div>
    </div>
<div>

 <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
       value="/wEWAwLktbDGDgKM54rGBgK7q7GGCMYnNq57VIqmVD2sRDQqfnOsgWQK" />
</div>

<script type="text/javascript">
//<![CDATA[
Sys.Application.initialize();
//]]>
</script>
</form>
</body>
</html>

From this page result, if you click Button1 and perform the full-page postback, you get this entire bit of code back in a response — even though you are interested in updating only a small portion of the page! Again, the reason for this is because it is not using any AJAX capabilities at all. However, if you click Button2 — the button specifically put in place to work with the underlying AJAX capabilities of the page — you send the request that is shown in Listing 2-8 to the back-end server.

Example 2-8. The asynchronous request from the ASP.NET AJAX page
POST /AJAXWebSite/Default.aspx HTTP/1.1
Accept: */*
Accept-Language: en-US
Referer: http://localhost.:62203/AJAXWebSite/Default.aspx
x-microsoftAJAX: Delta=true
Content-Type: application/x-www-form-urlencoded; charset=utf-8
Cache-Control: no-cache
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.
         50727;
Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.21022; .NET CLR 3.0.04506)
Host: localhost.:62203
Content-Length: 334
Proxy-Connection: Keep-Alive
Pragma: no-cache

ScriptManager1=UpdatePanel1%7CButton2&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%
2FwEPDwULLTE4NzE5NTc5MzQPZBYCAgQPZBYCAgMPDxYCHgRUZXh0BRQxMS8zLzIwMDcgMjoxNzo1NSBQTW
RkZHZxUyYQG0M25t8U7vLbHRJuKlcS&__EVENTVALIDATION=%2FwEWAwKCxdk9AoznisYGArursYYI1844
hk7V466AsW31G5yIZ73%2Bc6o%3D&Button2=Click%20to%20get%20machine%20time%20using%20Aj
ax

The response that comes back in return from this request is presented here in Listing 2-9:

Example 2-9. The asynchronous response from the ASP.NET AJAX page
HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Thu, 03 Jul 2008 10:44:25 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Content-Length: 796
Connection: Close

239|updatePanel|UpdatePanel1|
                <span id="Label2">07/3/2008 5:44:25 AM</span>
                <br />
                <br />
                <input type="submit" name="Button2" value="Click to get machine
                 time using AJAX" id="Button2" />

|172|hiddenField|__VIEWSTATE|/wEPDwULLTE4NzE5NTc5MzQPZBYCAgQPZBYEAgMPDxYCHgRUZXh0BR
QxMS8zLzIwMDcgMjoxNzo1NSBQTWRkAgcPZBYCZg9kFgICAQ8PFgIfAAUUMTEvMy8yMDA3IDI6MTc6NTggU
E1kZGQ4ipZIg91+XSI/dqxFueSUwcrXGw==|56|hiddenField|__EVENTVALIDATION|/wEWAwKCz4mbCA
K7q7GGCAKM54rGBj8b4/mkKNKhV59qX9SdCzqU3AiM|0|asyncPostBackControlIDs|||0|postBackCo
ntrolIDs|||13|updatePanelIDs||tUpdatePanel1|0|childUpdatePanelIDs|||12|panelsToRefr
eshIDs||UpdatePanel1|2|asyncPostBackTimeout||90|12|formAction||Default.aspx|22|page
Title||My ASP.NET AJAX Page|

To view the requests and responses in a similar manner to what is presented in Listing 2-9, you can use any HTTP sniffer. I recommend Fiddler found at www.fiddlertool.com.

From Listing 2-9 here, you can see that the response is much smaller than an entire Web page! Also notice that this output includes the HTTP header as well. In fact, the main part of the response is only the code that is contained within the UpdatePanel server control and nothing more. The items at the bottom deal with the ViewState of the page (as it has now changed) and some other small page changes.

When not using AJAX and a postback is occurring, the entire page is reloaded into the browser. In this case, there is a visible flicker of the browser as the previous rendering is removed and the new rendering is displayed. The user usually notices this interruption, and this can interfere with their train of thought when working with your application.

This is quite different from the smooth responsiveness users are accustomed to when working with desktop applications and the jarring nature of these types of Web applications can be disconcerting or annoying to end users. This click-pause-flicker pattern is what the UpdatePanel control helps you overcome. A Web application can now be almost as responsive as a thick client Windows application! The small delays required for passing data between the client and the server are still there, but they are much easier to tolerate now. In many cases, the user may not even notice these delays, because you can distribute the updates so they do not all occur at once.

When you have the smaller responses for the page that perform the page changes that you are really looking for (and nothing more), you will find that the pages are quite a bit better overall. First off, the performance of the page is going to be considerably better (even more so for larger pages) as you are only updating the sections of the pages that need to change and you are not continually moving repetitive code around to be transmitted on the wire and then in turn, interpreted by processing engines.

Probably the most important benefit is for the end users who are now working with the UI of an application that has quite a bit more fluidity to it. The application will feel more responsive to the end user.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset