Your Ad Here
Google

Monday, March 05, 2007

 

Ajax in Action - ajax allows you to make server side calls without doing a postback

Introduction

I love AJAX, it really cleans my dishes. Unfortunately, in this article we will not be talking about washing detergent. If you like you can visit Clean My Dishes for more details. In this article we will be talking about AJAX (Asynchronous JavaScript and XML). All you need to know right now is that AJAX allows you to make server side calls without doing a postback.

Downloading the AJAX.NET Library

First of all, you need to download the AJAX.NET library created by Michael Schwarz. Now that you have downloaded the library and made the reference to the DLL in your project, we can start some dirty stuff.

What are we going to do?

Okay, here is what we are going to do. We are going to make a dropdown list using " +
html.join("") + "";
}
}
Let me first explain the FillDropDownList() method. UsingAjax is the name of the class which contains the GetDropDownListData method which we implemented a few moments ago. We call FillDropDownList_CallBack() which contains the actual code to populate the dropdown list.

Take a look at the line below:

document.getElementById("Display").innerHTML =
"
";

for(var i=0;i"> s[s.length] = " ";
s[s.length] = " ";
s[s.length] = " ";
s[s.length] = "";
}
s[s.length] = "
" + ds.Tables[0].Rows[i].ProductID + "" + ds.Tables[0].Rows[i].ProductName + "" + ds.Tables[0].Rows[i].QuantityPerUnit + "

";

document.getElementById("Display1").innerHTML = s.join("");
}
}
GetResults() method calls the server side method "GetProductsByID".

[Ajax.AjaxMethod]
public DataSet GetProductsByID(int categoryID)
{
string query = "SELECT * FROM Products WHERE CategoryID = @CategoryID ";
SqlConnection myConnection = new SqlConnection(GetConnectionString());
SqlCommand myCommand = new SqlCommand(query,myConnection);

myCommand.Parameters.Add("@CategoryID",categoryID);
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();

ad.Fill(ds);
return ds;
}
So, there you go now. When you select an item from the dropdown, your DataGrid will pull up new results without having to refresh the page. In other words, there will be no postback.

You should also make a BindControls() method that will populate the controls when the page loads. Here is my implementation of the BindControls() method. Keep in mind that we have already implemented the FillDropDownList() method above.

function BindControls()
{
FillDropDownList();
}
After making the BindControls method you just need to call it when the page loads.


You also need to add these settings in the web.config file:






...


For your convenience I have attached the zip file which contains all the files you need for this project. I hope you like the article, happy coding!

Labels:


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?