Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.Net AJAX Begineers Guide

0.00/5 (No votes)
26 Nov 2012 2  

Introduction 

Hello readers  this is my first effort to write here   it is focused  to help the beginners who are looking to start working with ASP.Net AJAX  this article will help you to take a overview of how ASP.Net AJAX works  later i will show you working example  .  As its my first effort  i appreciate to point out my mistakes.  This article assume that you already have basic knowledge about web applications and client server programming model .  Last but not least i will post further articles on How to use AJAX with Rest Web services .  

What is AJAX   

AJAX are  client side  UI patterns  . What does it Means ?before that  lets think on simple workflow where client requests  for a resource on server  and server receives the request and response  back to client with resource all this communication is done via HTTP and all page is rendered in HTML .  Now Lets think if you have a information page where user selects a Region and on the basics of selected region list of cities is displayed on dropdownlist   well thats fine it works perfect but here we have one problem for every time when user select a different region then page is posted back to server com-on this increase the network traffic and server load its not a good performance practice .AJAX resolves this problem by rendering a partial page instead of full page post back to server   . So AJAX is nothing its client side  UI pattern and now its standard for developing robust  web applications  .  

How AJAX Work?  

Technically speaking AJAX combines the XMLHTTP components with Java Script library  it works via  XMLHTTP request to achieve the partial rendering to server instead of full page postback. So What happens when user tries to update or get the information it generates the asynchronous call to server and then server respond with updated data no page refresh will happen.  For example you have to update the total products sold on your grid view  which implements the AJAX so it generate a partial asynchronous call to server and server will respond with updated total . I hope its clear .   

 How to Install AJAX With Visual Studio 2008 AND 2010  

I assume that you are starter and you dont know about the AJAX toolkit its basic requirement to use AJAX with you web page .

Installing AJAX Toolkit Visual on Studio 2008 

Go to following URL and download the AJAX toolkit for visual studio 2008  i am not going to explain how to install it because this site explain it very well ): 

 http://www.aspnettutorials.com/tutorials/ajax/installing-ajax-toolkit-2008.aspx 

Installing AJAX Toolkit Visual on Studio 2010 

For visual studio 2010 please see this site .  

 http://weblogs.asp.net/yousefjadallah/archive/2010/04/16/installing-ajax-control-toolkit-4-in-visual-studio-2010.aspx

Code Example :

Well now we are done with installing the tool kit its time to see the practical example .

Scanerio  

Lets take the above discussed example of Regions user will select a region and on that selected region second dropdownlist will show the cities so i will use the partial postback approach .

Creating AJAX Enable Web Page Using AJAX Update Pannel and Script Manager  

  1. Add a scriptManager on your asp.net markup page
  2. Add a Update Pannel
  3. Add content Template
  4. Inside your contant Template add dropdownlists
  5. Then create a Trigger  which actually register the Regions SelectedIndexChanged Event  its actually a caller which will generate a asynchronous call to server .                                                                        

What is Script Manager ?

 scriptManager  its part of server components it manages the client script for AJAX enable web pages it registers the script for Microsoft AJAX library .

What is Update Panel? 

Well Update panel is most important control it enable the partial page call instead of full page post back Update Panel   has two child tags <contentTemplate>  and< trigger >  content Template is responsible for holding the contents of panel you can put simple test or a control and Trigger tag trigger the call on a particular event so Here you can see markup portion of my code  .

Markup Code Description :

So here i took a ScriptManager  and Update Panel   I am putting my dropdown lists inside the Content Template as i already explained that content template is used to put code and text area here i am putting the dropdownlist  and a small text with cities  then on Triggers Tag  on asp:AsyncTrigger  i registered the Regions selectedItemChanged Event  every time when user will select the region it will trigger partial asynchronous call to server and cities will be update . This is simple beauty of AJAX .  

<div id="DropDownRegions"> 
<asp:ScriptManager ID="Sm" runat="server" />
<asp:UpdatePanel runat="server" >
<ContentTemplate> 
  <asp:DropDownList ID="drpRegions" runat="server" AutoPostBack="True" 
        Height="37px" onselectedindexchanged="drpRegions_SelectedIndexChanged" 
        Width="163px">
    </asp:DropDownList>
   <br /> 
    Check Cities <br />
    <asp:DropDownList ID="Cities" runat="server" Height="19px" Width="168px">
    </asp:DropDownList>
    </ContentTemplate> 
 <Triggers >
<asp:AsyncPostBackTrigger ControlID="drpRegions" EventName = "SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>     <span style="white-space: normal;"> </span>

C# code :

On C# code Behid please do the following steps  

  1. Create a List of Regions using List instead of Getting data from database i am creating a List of Regions which will add regions on Page_Load Event  .
  2. Register a event drpRegions  its SelectedItemChanged Event so whenever dropdownlist selected value will be changed it will raise a event on that event we can check which region is selected and we can take decisions which City list to be added to City dropdownlist . We are done Please see the C# Code below . 
  

 Now on Code Behind i am populating the Regions with List instead of database table .
// Binding List with Region Dropdownlist at PageLoad Event.
        { 
       page_Load {

            if (!IsPostBack)
            { 
                List<string> Regions = new List<string>();
                Regions.Add("South");
                Regions.Add("East");
                Regions.Add("West");
                Regions.Add("North");
                Regions.Add("EastWest"); 
                drpRegions.DataSource = Regions;
                drpRegions.DataBind(); 
            }    
}                                                                                    Now on Selected Index Change Event it will get the region name and see which region match with cities list .  
// adding city list according to region selected
 
protected void drpRegions_SelectedIndexChanged(object sender, EventArgs e)
        { 
                           List<string> Punjab = new List<string>();
                Punjab.Add("Lahroe"); 
                Punjab.Add("okara");
                List<string> sindh = new List<string>(); 
                sindh.Add("Karachi"); 
                sindh.Add("Quoteata"); 
                List<string> Buloschistan = new List<string>();
                Buloschistan.Add("Quetta");
                Buloschistan.Add("Cheltan");
                List<string> Serhad = new List<string>();
                Serhad.Add("Peshwar");
                Serhad.Add("Kohat");
                List<string> Kashmir = new List<string>();
                Kashmir.Add("Bagh");
                Kashmir.Add("DheerKot");
                Kashmir.Add("Rawlakot");
                Kashmir.Add("Mirpur");
                
            if(drpRegions.SelectedValue==" South ")
            {
                this.Cities.DataSource = Punjab;
                this.Cities.DataBind();
            } 
            else if (drpRegions.SelectedValue == " East ")
            {
                this.Cities.DataSource = sindh;
                this.Cities.DataBind();                                                              }
            else if (drpRegions.SelectedValue == " West ")
            {
                this.Cities.DataSource = Buloschistan;
                this.Cities.DataBind();
            }
            else if (drpRegions.SelectedValue == " North ")
            {
                this.Cities.DataSource = Serhad;
                this.Cities.DataBind(); 
            }
            else if (drpRegions.SelectedValue == " EastWest ")
            { 
                this.Cities.DataSource = Kashmir;
                this.Cities.DataBind();
            }
        } 

Advantages   

  1. Its Increase the performance . 
  2. Reduce Network Traffic .
  3. Reduce Server Load  
  4. Easy Nevigation
DisAdvantages

Well when you try to hit the back or refresh button it shows a different behavior )  it could be fixed by good programming practices . 

Who Uses AJAX 

Google search , google maps , Facebook , are very common examples of AJAX. 

  

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here