Click here to Skip to main content
Click here to Skip to main content

Easiest way to implement ASP.NET Ajax into your applications

By , 11 May 2007
 

Screenshot - result.jpg

Introduction

Asynchronous JavaScript and XML are now the needed for new generation websites. The ASP.NET Ajax way is very easy. We just place a few lines of code in the web.config file and start using ASP.NET Ajax tags. But you should download Ajax first from Microsoft.

System requirements:

  • Microsoft .NET Framework Version 2.0
  • Internet Explorer 5.01 or later
  • Windows 2000 / Windows Server 2003 / Windows Vista / Windows XP

After downloading and installing Ajax, you will get an additional option in your .NET toolbox, so it will look like this:

Screenshot - one.jpg

Using ASP.NET Ajax

There are two main ways to use ASP.NET Ajax. The first is to create a new ASP.NET Ajax-enabled website.

Screenshot - two.jpg

The second is to make changes in your existing ASP.NET 2.0 website. You must add the following lines in your web.config files, in this case. The following lines should be added under <system.web>:

<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" 
    type="System.Web.Script.Services.ScriptHandlerFactory, 
    System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
    PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" 
    type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, 
    Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" 
    validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, 
    System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, 
    PublicKeyToken=31bf3856ad364e35"/>
</httpModules> 

If you're wondering why I add these lines to the web.config file, the answer is that these lines can be found in system C or other system directory \Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\web.config

If you don't do this, then you will get the "sys is undefined" JavaScript error and your Ajax will not work properly.

So, cheer up, now your application is ready to implement in .NET 2.0. First place a "script manager" and then an "update panel." Now if any control in the update panel requests the server, only the part within the update panel will be submitted to the server. This is very useful when your page is frequently posted back.

Here I am giving you a very simple and useful example, which occurs often while making a dynamic website. The example is when data is dynamically filled in the drop-down list. The user chooses a country, which should then cause only information pertinent to the selection to be displayed. To remove post-back in this case, you can use ASP.NET Ajax, as given in my example.

For the ease of your understanding, I don't use anything in my example except what's necessary and illustrative. I use XML database for this example, but you can use other databases. After design completion, it looks like this:

Screenshot - three.jpg

My naming convention is as follows:

ddlCountry Drop-down list for country
ddlState Drop-down list for state
lblMsg And a label

Now ddlCountry is dynamically filled by the XML database at the pageload event. For this purpose, I call a function fillCountry(). It is called only once to fill in the drop-down list ddlCountry.

Page Load Event

    ''' <summary>
    ''' On page load the drop down for choose country is filled, 
    ''' by a function fillCountry()
    ''' </summary>
    ''' <param name="sender" />
    ''' <param name="e" />
    ''' <remarks />
Protected Sub Page_Load(ByVal sender As Object, 
    ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            fillCountry()
        End If
End Sub

Sub routine fillCountry

The fillCountry() subroutine is used to fill in ddlCountry after reading the XML file in the dataset. It uses listitem to fill the drop-down list. The listitem text and listitem value are provided dynamically from the dataset. At the end, listitem is added to the drop-down list.

   ''' <summary>
    ''' This subroutine is used to dynamically fill the drop down list for  
    ''' country 
    ''' </summary>
    ''' <remarks />
    Private Sub fillCountry()
        Dim ds As New DataSet()
        Dim lst As ListItem    
            ''' lists items to be added to drop down list after 
            ''' assigning the text and value
        Dim i As Integer = 0
        If Not IsPostBack() Then
            ddlCountry.Items.Clear()
        End If

        ds.ReadXml(Server.MapPath("App_Data\country.xml"))
        lst = New ListItem()
        lst.Text = "--Choose Country--"
        lst.Value = "0"
        ddlCountry.Items.Add(lst)
        For i = 0 To ds.Tables(0).Rows.Count - 1
            lst = New ListItem()
            lst.Text = ds.Tables(0).Rows(i)(0)
            lst.Value = ds.Tables(0).Rows(i)(1)
            ddlCountry.Items.Add(lst)
        Next
    End Sub 

The country drop-down list is dynamically filled by the above code.

Select index change event

Protected Sub ddlCountry_SelectedIndexChanged(ByVal sender As Object, 
            ByVal e As System.EventArgs)
        ddlState.Enabled = True
        fillState(ddlCountry.SelectedItem.Value.ToString().Trim())
        lblMsg.Text = "You are selected " 
            + ddlCountry.SelectedItem.Text
    End Sub

On the change of the drop-down selection, the state drop-down list (ddlState) is enabled and the ddlState drop-down is dynamically filled by the function fillState(country's selected item value).

Sub routine fillState(CountryID)

If you have a close look at the code below, you will find the line ddlState.Items.Clear(). It is there to clear the ddlState every time before dynamically filling data into it. If this line is not included, then each time this function is called it will not remove the previous data, only add new items into it. Now again a new thing:

lst = New ListItem()
lst.Text = "--Choose State--"
lst.Value = "0"

What these three lines do is add the first list item as "Choose State," so the user can easily understand that this drop-down is for choosing the state. Its value is 0 here, but you can make it -1 or some string as you prefer.

One last thing:

If ds.Tables(0).Rows(i)(2) = countryid Then
The above line filters the state data which belongs to the particular CountryID (See State.xml). If you are using another database, you do it by using the where condition in the SQL select statement.
    ''' <summary>
    ''' It fills the drop down for the state dynamically
    ''' </summary>
    ''' <param name="countryid" />
    ''' It accepts the select item value from the country drop down list
    ''' <remarks />
Private Sub fillState(ByVal countryid As String)
        Dim ds As New DataSet()
        Dim lst As ListItem
        Dim i As Integer = 0
        ddlState.Items.Clear()
        lst = New ListItem()
        lst.Text = "--Choose State--"
        lst.Value = "0"
        ddlState.Items.Add(lst)
        ds.ReadXml(Server.MapPath("App_Data\state.xml"))
        For i = 0 To ds.Tables(0).Rows.Count - 1
            If ds.Tables(0).Rows(i)(2) = countryid Then
                lst = New ListItem()
                lst.Text = ds.Tables(0).Rows(i)(0)
                lst.Value = ds.Tables(0).Rows(i)(1)
                ddlState.Items.Add(lst)
            End If
        Next

Conclusion

Now we can come to the conclusion that you can really enhance user interaction using ASP.NET Ajax. There are other items in the ASP.NET Ajax toolbox extension, as well. For example, "update progress" is for displaying progress in the ASP.NET Ajax panel when it takes too much time to update. Another example of ASP.NET Ajax is using it in "data grid;" it can remove the postback when you enable paging and shorting. In "calendar control," it also removes the post-back.

I hope you found this article useful. I hope to post more articles about the other features of ASP.NET Ajax.

History

  • May 11, 2007 - Original version posted

License

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

About the Author

Gaurav K Singh
Web Developer UTStarcom
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralEasiest, maybe; but not simplermemberkonamiman3419 Aug '08 - 2:02 
Just for the record, there is a very simple way to use AJAX with ASP.NET without having to install any external library nor using special controls.
 
Just create a new aspx file which will process the AJAX request, name it for example "ajaxmanager.aspx". Remove all the markup and leave only the page declaration:
 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ajaxmanager.aspx.cs" Inherits="WebApplication1_ajaxmanager" %>
 
Then, catch the page_load event and write the response data directly to the Response object. For example, for a rather stupid service that expects a parameter named "theText" and returns it converted to upper case:
 
protected void Page_Load(object sender, EventArgs e)
{
    string text=Request.Params["theText"];
 
    text=text.ToUpper();
 
    Response.ContentType="text/plain";
    Response.Write(text);
    Response.End();
}
 
Do the ajax request from the client using whatever method you like (I personally use JQuery) and... done.
 
Ok, this is a somewhat brute force method and maybe not very friendly, but it is really the simplest one! Smile | :)
GeneralOne of the best Artical on TCP.memberMember 13490802 Mar '08 - 21:08 
i think this is very fine composed AJAX aritical for new commers.
 
very good work, Well done,
 
Walid

GeneralMarvellousmemberCuchuk Sergey7 Feb '08 - 4:53 
It's the best article i read - so thank you vary much for your clear explanation of ajax
 

 

Bugs:
to create folder App_Data and move here both xml files
GeneralGreatmemberHrushikesh Mokashi30 Nov '07 - 2:54 
Thanx a lot dude/sir. Because of guys like you we people can bare this industry Smile | :) . Most simple and still helpful article on code project i think.
 
hrushikesh

GeneralGreat job !membertungth-it31 Oct '07 - 23:00 
Many thanks !
I'm new to asp.net Ajax, about 24h or more. And your thread really help !
Thank again !
GeneralBig Helpmemberjanette thurgood19 Sep '07 - 7:04 
Thanks for including specific codes necessary for config file - worked like a charm. Thanks again.
Generalumm...memberEdelman15 May '07 - 2:17 
so, postbacks actually get turned into AJAX? I don't quite understand where the AJAX comes in here, and how do you control what gets posted back and what doesn't? Are you saying that we don't actually have any control over any of the javascript created? I'm really confused...it looks like this article just showed me how to filter a textbox, not use any AJAX. Unless it's as easy as adding those two AJAX components. But still, no control?
 
Help?
AnswerRe: umm...memberfloppy_Bop15 May '07 - 5:28 
The short answer is no. As usual in ASP.NET, Microsoft aims at none web developers and tries to make it easy for windows developers. That being said, you can write as much javascript in you page (ASPX) as you want and make use of Microsoft AJAX Library which is pretty cool. If you want to make use of other libraries (without having a really heavy client by putting them next to Microsoft AJAX Library) you have to make sure that they make there AJAX request with the header "Content-Type application/json; charset=utf-8" (if you don't want XML) and you have to make an implementation of Microsoft DateTime serialization/deserialization.
 

 
If the world should blow itself up, the last audible voice would be that of an expert saying it can't be done - Peter Ustinov

GeneralNice ArticlememberMarwa ElBadry14 May '07 - 20:05 
It is what I need to start learning AJAX.
 
Thanks
 
Marwa ElBadry
GeneralSimple is bettermemberJomit Vaghela14 May '07 - 18:38 
A good simple example....
 
cheers,
GeneralGreat Jobmembermerlin98111 May '07 - 8:56 
Very nice and succicent. Great job
 


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I get my developer tools from Merlin A.I. Soft

I get my news and jokes from Daily Roundup

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

GeneralExcellentmemberSouthmountain11 May '07 - 6:44 
I need it!

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 11 May 2007
Article Copyright 2007 by Gaurav K Singh
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid