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
Rate this:
Please Sign up or sign in to vote.

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
No Biography provided

Comments and Discussions

 
GeneralOne of the best Artical on TCP. PinmemberMember 13490802-Mar-08 21:08 
GeneralMarvellous PinmemberCuchuk Sergey7-Feb-08 4:53 
GeneralGreat PinmemberHrushikesh Mokashi30-Nov-07 2:54 
GeneralGreat job ! Pinmembertungth-it31-Oct-07 23:00 
GeneralBig Help Pinmemberjanette thurgood19-Sep-07 7:04 
Generalumm... PinmemberEdelman15-May-07 2:17 
AnswerRe: umm... Pinmemberfloppy_Bop15-May-07 5:28 
GeneralNice Article PinmemberMarwa ElBadry14-May-07 20:05 
GeneralSimple is better PinmemberJomit Vaghela14-May-07 18:38 
GeneralGreat Job Pinmembermerlin98111-May-07 8:56 
GeneralExcellent PinmemberSouthmountain11-May-07 6:44 

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
Web03 | 2.8.140421.2 | Last Updated 11 May 2007
Article Copyright 2007 by Gaurav K Singh
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid