Click here to Skip to main content
Click here to Skip to main content
Go to top

Creating your first ASP.NET AJAX 1.0 Application

This shows how to AJAX-enable an existing ASP.NET web page by using Microsoft’s ASP.NET AJAX Extensions. The UpdatePanel control provided by the framework makes it really easy to start with AJAX programming by defining the areas of the page you want to update independently without a full page reload

Editorial Note

This article is in the Product Showcase section for our sponsors at CodeProject. These reviews are intended to provide you with information on products and services that we consider useful and of value to developers.

Introduction

Over the last year or so, AJAX has taken the web development world by storm. AJAX is short for Asynchronous JavaScript and XML and is an approach to building dynamic web applications that behave less like the static web pages we're used to and more like desktop applications.

At the heart of AJAX is the XmlHttpRequest object, a component originally designed by Microsoft and used to provide the rich Outlook-like interface of Exchange Web Access. JavaScript on a web page can use an instance of XmlHttpRequest to send requests to the web server that generated the page and then use the response to update part of the page, without the browser having to reload everything. This can make the application a lot quicker – instead of the entire page having to be transmitted and rendered, the browser just fetches what's needed to update the current page.

Although the technologies that support AJAX-style web apps have been around for years, they weren't widely used until the introduction of frameworks that made dealing with the extra complexity, not to mention cross-browser differences, possible. Microsoft's ASP.NET AJAX framework is one of the most recent, and has just been released as version 1.0, following a year of pre-releases that used the code name "Atlas".

This article shows you how to AJAX-enable an existing ASP.NET web page by using Microsoft's ASP.NET AJAX Extensions. The UpdatePanel control provided by the framework makes it really easy to start with AJAX programming by defining the areas of the page you want to update independently without a full page reload.

Once you've understood the basics, you'll use an InnerWorkings coding challenge that provides a sample AJAX-enabled bug tracking website to help you really understand how to use the AJAX Extensions.

ajax-app

What is Microsoft ASP.NET AJAX?

Microsoft ASP.NET AJAX is a free framework designed to make it easier to write modern AJAX-style applications using ASP.NET. There are two parts to the framework – a cross-browser JavaScript library and a set of server-side ASP.NET controls. The JavaScript library goes beyond simply enabling AJAX apps and provides object-oriented extensions to JavaScript to make it easier to write complex applications that need to process a lot of data in the browser. On the server-side, a set of new and enhanced ASP.NET controls make it possible to write AJAX applications by simply adding controls to a page, just as with non-AJAX applications. In fact, you don't have to write a single line of JavaScript to create a fully-featured AJAX application.

As well as ASP.NET AJAX itself, there are two other downloads available to add AJAX functionality to your site. The AJAX Futures CTP (Community Technical Preview) is a collection of new features which will be added to the main AJAX Extensions framework in the future. The AJAX Control Toolkit contains prewritten components like panels that can be dragged around the page and rating controls to enable users to submit feedback.

What's an InnerWorkings Developer Coding Challenge?

An InnerWorkings Developer coding challenge is a sample of code in Visual Studio that has a couple of key pieces missing. Each challenge includes selected reference links chosen specifically so you can easily find out how to fill in the blanks, complete the sample app, and learn about a new technology at the same time. Once you're finished, InnerWorkings Developer automatically checks your code so you can be sure you've solved the challenge correctly and that you really understand what you've learned.

The coding challenges are designed to take you to the heart of the technology you want to learn more about, focusing on the most important, practical features. Because everything has been set up for you, you can dive straight in and start coding.

InnerWorkings Developer has a library of hundreds of challenges on topics from ASP.NET to Windows Communication Foundation. For more information, have a look at our catalog.

How Does the UpdatePanel Work?

The UpdatePanel is designed to be the easiest possible way to AJAX-enable your site, focusing on the most important feature of AJAX: restricting updates to an area within a page instead of requiring a full refresh. Although it completely changes how requests are made by the browser, the UpdatePanel is written in such a way that your pages execute normally, which means you don't have to rewrite any controls or server-side logic.

As the browser loads the AJAX framework, a JavaScript onsubmit handler is added to every form element on the page. When the form submits, the handler checks whether this should be a "partial update" – one handled by an update panel. If so, it collects all the data being sent to the server, repackages it, and sends it, not as a regular browser request, but using the XmlHttpRequest object. In the browser, the onsubmit handler now returns false, effectively telling the browser to cancel the full page refresh. Meanwhile, the request has made its way to your web server looking just like a normal request with one difference: an extra HTTP header lets the AJAX infrastructure know that this is a partial update.

The page executes as normal and the output is collected ready to be sent to the browser. Just before it's sent however, another bit of AJAX magic kicks in. Everything that isn't needed for the UpdatePanel is stripped out and some extra data is sent (including updated hidden fields and ViewState for controls not included in the UpdatePanel).

When this arrives back at the browser, the JavaScript library updates everything, including the contents of the UpdatePanel, but also all the extra data. If your ASP.NET page updates the page title or even the page's CSS styles, all of these are updated automatically.

Using the UpdatePanel

Despite all this automatic support, using the UpdatePanel couldn't be simpler. There's a little install work – once the AJAX extensions are installed, there are only a couple of additions to your web.config file to paste in. (The easiest way to add these is simply to copy the sample config file which should be installed to C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\web.config or somewhere similar, depending on where you installed the extensions.) After that you can AJAX-enable your website by adding just two tags to your webpage: a ScriptManager and the UpdatePanel itself.

The ScriptManager control manages the AJAX JavaScript libraries and writes <script> tags to tell the browser what to download. This process is mostly automatic, although you can also configure the control to include your own scripts, or to generate JavaScript for calling web services hosted on your server. To add a ScriptManager to your page, just add a ScriptManager tag to any server-side form within the page.

<form runat="server">
    <asp:ScriptManager runat="server" />
    <!--<span class="code-comment"> rest of form continues… --></span>
</form>

The UpdatePanel is used to define the section of the page that should update without a full page refresh. To use the default features, just enclose the part of the page you want to AJAX-enable in a matching pair of UpdatePanel and ContentTemplate tags. In the example below, the SubmitButton and ResponseLabel tags are inside the UpdatePanel – when the SubmitButton is clicked, a message appears without the page refreshing. To see how the page updates without using AJAX, you can comment out the UpdatePanel and ContentTemplate tags, leaving the Button and Label tags in place.

<!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>Ajax test page</title>
</head>
<body>
    <form id="AjaxTestForm" runat="server">
    <asp:ScriptManager runat="server" />
    <p>
    What's your name?<br />
    <asp:TextBox ID="NameText" runat="server" />
    </p>
    <p>
    When's your birthday?<br />
    <asp:TextBox ID="BirthdayText" runat="server" /><br />
    </p>
    <asp:UpdatePanel runat="server">
        <ContentTemplate>
            <asp:Button ID="SubmitButton" runat="server" Text="Submit" 
                        OnClick="SubmitButton_Click" /><br />
            <asp:Label ID="ResponseLabel" runat="server" />
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>

    <script runat="server" language="csharp">
    private void SubmitButton_Click(object sender, EventArgs e)
    {
        DateTime birthday = DateTime.Parse(BirthdayText.Text);
        if (birthday.Date < DateTime.Today.Date)
        ResponseLabel.Text =
               string.Format("Sorry {0}, looks like I missed your birthday!",
                          NameText.Text);
        else if (birthday.Date > DateTime.Today.Date)
            ResponseLabel.Text = 
               string.Format("Thanks {0}, I'll put that date in my diary!", 
                             NameText.Text);
        else
            ResponseLabel.Text = string.Format("Happy Birthday {0}!", 
                                               NameText.Text);
    }
    </script>
</body>
</html>

Try It Out

As you can see, adding the UpdatePanel to an existing page couldn't be much simpler, but there's a lot more to the AJAX extensions than just the UpdatePanel. A great place to start if you want to see what's possible is the ASP.NET AJAX showcase.

Next, download the free ASP.NET AJAX Drill from InnerWorkings and see how to use the UpdatePanel in a real application. Once you've solved the challenges it contains, you'll know you're ready to start using AJAX in your next project.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Michael O'Brien lives in Dublin, Ireland where he works for InnerWorkings. He currently concentrates on the software that allows InnerWorkings Developer to check code solutions submitted to the InnerWorkings code judging engine. When he's not knee-deep in System.Reflection, he likes to play with ASP.NET and a little bit of Ruby.

Comments and Discussions

 
GeneralVideo tutorial about Gaia Ajax Widgets PinmemberDoodie Woddy Doodlechips11-Feb-08 14:03 
GeneralAsp.net components PinmemberPOOR MAN6-Jul-07 2:48 
Generalajax web application Pinmemberveerbala4-Apr-07 18:45 
GeneralRe: ajax web application PinmemberMichael O'Brien11-Apr-07 4:40 
GeneralRe: ajax web application PinmemberNorman Katz24-Apr-07 8:48 
GeneralRe: ajax web application PinmemberMichael O'Brien24-Apr-07 21:26 
GeneralRe: ajax web application PinmemberNorman Katz25-Apr-07 19:33 
Thanks for the link Michael. I've already had great success with Ajax.Net from Michael Schwarz
http://www.ajaxpro.info . I was just hoping the UpdatePanel could save me even more coding. Unfortunately, like other 3rd party web controls, it hides the code-behind handlers so you get what you get. I will take a look at the lower level Microsoft methods since I also like some of the Ajax toolkit controls like the tab control and the ratings control. I tried running a project with both MS Ajax and AjaxPro and was not successful, probably due to too many httpHandler conflicts. So I'd like to settle one one or the other, but both have their advantages.
GeneralRe: ajax web application Pinmemberpraveeav30-Jul-07 22:59 
GeneralYou can see PinmemberChiranjibC7-Feb-07 1:35 
GeneralRe: You can see PinmemberVasudevan Deepak Kumar19-Mar-07 4:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140926.1 | Last Updated 5 Feb 2007
Article Copyright 2007 by Michael O'Brien / InnerWorkings
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid