Wrox Home  
Search
Professional ASP.NET 3.5 : in C# and VB
by Bill Evjen, Scott Hanselman, Devin Rader
March 2008, Paperback


Excerpt from Professional ASP.NET 3.5: in C# and VB

ASP.NET AJAX in ASP.NET 3.5 and Visual Studio 2008

by Bill Evjen

Prior to Visual Studio 2008, the ASP.NET AJAX product used to be a separate installation that you were required to install on your machine and the Web server that you were working with. This release gained in popularity quite rapidly and is now a part of the Visual Studio 2008 offering. Not only is it a part of the Visual Studio 2008 IDE, the ASP.NET AJAX product is also baked into the .NET Framework 3.5. This means that to use ASP.NET AJAX, you don't need to install anything if you are working with ASP.NET 3.5.

ASP.NET AJAX is now just part of the ASP.NET framework. When you create a new Web application, you do not have to create a separate type of ASP.NET application. Instead, all ASP.NET applications that you create are now AJAX-enabled.

If you have already worked with ASP.NET AJAX prior to this 3.5 release, you will find that there is really nothing new to learn. The entire technology is seamlessly integrated into the overall development experience.

Overall, Microsoft has fully integrated the entire ASP.NET AJAX experience so you can easily use Visual Studio and its visual designers to work with your AJAX-enabled pages and even have the full debugging story that you would want to have with your applications. Using Visual Studio 2008, you are now able to debug the JavaScript that you are using in the pages.

In addition, it is important to note that Microsoft focused a lot of attention on cross-platform compatibility with ASP.NET AJAX. You will find that the AJAX-enabled applications that you build upon the .NET Framework 3.5 can work within all the major up-level browsers out there (e.g., Firefox and Opera).

Developing with ASP.NET AJAX

There are a couple of types of Web developers out there. There are the Web developers who are used to working with ASP.NET and who have experience working with server-side controls and manipulating these controls on the server-side. Then there are developers who concentrate on the client-side and work with DHTML and JavaScript to manipulate and control the page and its behaviors.

With that said, it is important to realize that ASP.NET AJAX was designed for both types of developers. If you want to work more on the server-side of ASP.NET AJAX, you can use the new ScriptManager control and the new UpdatePanel control to AJAX-enable your current ASP.NET applications with little work on your part. All this work can be done using the same programming models that you are quite familiar with in ASP.NET.

In turn, you can also use the Client Script Library directly and gain greater control over what is happening on the client's machine. Next, this article looks at building a simple Web application that makes use of AJAX.

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 1) 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.

Figure 1
Figure 1

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 the 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 1.

Listing 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="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>


<!-- Configuraiton removed for clarity -->
  
</configuration>

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

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.

Listing 2: A simple ASP.NET 3.5 page that does not use AJAX

VB

<%@ Page Language="VB" %>


<script runat="server">
    Protected Sub Button1_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs)


        Label1.Text = DateTime.Now.ToString()
    End Sub</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>

C#

<%@ Page Language="C#" %>


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

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

Listing 3: 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.

Building a Simple ASP.NET Page with AJAX

The next step is to build upon the page from Listing 2 and add 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.

In the Visual Studio 2008 toolbox, you will find a new section titled AJAX Extensions. This new section is shown in Figure 2.

Figure 2
Figure 2

From AJAX Extensions, add a ScriptManager server control to the top of the page and include the second Label and Button control inside the UpdatePanel control. The UpdatePanel control is a template server control and allows you to include any number of items within it (just as other templated ASP.NET server controls). When you have your page set up, it should look something like Figure 3.

Figure 3
Figure 3

The code for this page is shown in Listing 4.

Listing 4: A simple ASP.NET AJAX page

VB

<%@ Page Language="VB" %>


<script runat="server">
    Protected Sub Button1_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs)
        Label1.Text = DateTime.Now.ToString()
    End Sub


    Protected Sub Button2_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs)
        Label2.Text = DateTime.Now.ToString()
    End Sub
</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>

C#

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

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 final result is presented in Figure 4.

Figure 4
Figure 4

When you first pull up the page from Listing 4, the code of the page is quite different from the page that was built without using AJAX. Listing 5 shows the page results that you will see.

Listing 5: 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&t=633285028458684000" type="text/javascript"></script>


<script src="/AJAXWebSite/ScriptResource.axd?
 d=FETsh5584DXpx8XqIhEM50YSKyR2GkoMoAqraYEDU5_
 gi1SUmL2Gt7rQTRBAw56lSojJRQe0OjVI8SiYDjmpYmFP0
 CO8wBFGhtKKJwm2MeE1&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&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 there, 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! However, if you click Button2—the AJAX button—you send the request shown in Listing 6.

Listing 6: 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.21004; .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 for this request is shown in Listing 7:

Listing 7: The asynchronous response from the ASP.NET AJAX page

HTTP/1.1 200 OK
Server: ASP.NET Development Server/9.0.0.0
Date: Sat, 03 Nov 2007 19:17:58 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">11/3/2007 2:17:58 PM</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|

From Listing 7 here, you can see that the response is much smaller than an entire Web page! 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.

This excerpt is from Chapter 19, "ASP.NET AJAX," of the upcoming, Professional ASP.NET 3.5: in C# and VB (Wrox, Feb-2008, ISBN: 978-0-470-18757-9). Bill Evjen (St. Louis, MO) is one of the more active proponents of the .NET technologies. He has been involved with .NET since 2000 and has founded the International .NET Association, which represents more than 500,000 members worldwide. In addition to working in the .NET world, Bill is a Technical Director serving in the office of the Chief Scientist for the international news and financial services company Reuters. Bill is the lead co-author of the upcoming (Feb-2008) Professional ASP.NET 3.5: in C# and VB and the best-selling Professional ASP.NET 2.0. Other related articles of interest by Bill and his co-authors, Scott Hanselman and Devin Rader, include ASP.NET 3.5 Windows-Based Authentication, Manipulating ASP.NET Pages and Server Controls with JavaScript, Connecting to Oracle or Access from ASP.NET 2.0, Using the ASP.NET 2.0 SQL Server Cache Dependency, and ASP.NET 2.0 FileUpload Server Control.