Sunday, October 26, 2008

ASP.NET Ajax Request/Response using JQuery

Filling ASP.NET DropDown List using jQuery AJAX.

In this example, i'll demonstrate how to implement AJAX functionality on asp:DropDown change event, and to fill the other Dropdown list without using the ScriptManager class (that comes with ASP.NET AJAX Toolkit)

For this case, I'm using a Javascript Library called
jQuery. This must be downloaded and included before using the below source code. (http://jquery.com)

My form contains two DropDowns: Categories(ddlCategories) and Items(ddlItems). OnChange of the Category DropDown I will fill the Items DropDown.
<form id="form1" runat="server">
<asp:DropDownList ID="ddlCategories" runat="server">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Fruits</asp:ListItem>
<asp:ListItem>Vegetables</asp:ListItem>
<asp:ListItem>Desserts</asp:ListItem>
</asp:DropDownList>
<br />
<asp:DropDownList ID="ddlItems" runat="server"></asp:DropDownList>
</form>
    Here is my ASP.NET Desing View of the Form which shows these DropDowns. I have hardcoded the first DropDown with Categories: Fruits, Vegetables and Desserts. The Items DropDown is empty initially, since we will fill these through jQuery AJAX, when the onChange event of the Category DropDown will be fired.
    The Best thing is that we do not have to register any JavaScript Event with any control using our code behind file [ddlCategories.Attributes.Add()],  jQuery has the functionality where we can write our own onChange Event function. So here is my jQuery Code in which I will write the onChange function of the Categories DropDownList and call a C# function (or implement my AJAX) and then finally fill the Items DropDown.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

$(document).ready(function(){

$("#<%=ddlCategories.ClientID %>").change(
function()
{
var category = this.options[this.selectedIndex].value;
var ddlItems = document.getElementById("<%=ddlItems.ClientID%>");
ddlItems.options.length = 0;
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/getItems",
data: "{'category':'"+category+"'}",
dataType: "json",
success: function(msg)
{
var arrItems = msg.d.split("|");
for(var i=0; i< arrItems.length; i++)
{
var opt = document.createElement("option");
ddlItems.options.add(opt)
opt.text = arrItems[i];
opt.value = arrItems[i];
}
}
});
}
);
});
</script>
Any jQuery implementation should be inside $(document).ready() function. This is the root function that is called everytime any event occurs on our page. In the above code we have written our onChange function inside this [ as $("#ddlCategories").change() ]. Inside this function we are catching up the item that is selected. The actual request for a C# function or AJAX function can be done through jQuery's $.ajax() function. This function takes 6 parameters that can be explained as follows:
1.  type: this is the Request type that we are going to make. Normally it is of type post.
2.  contenType: ASP.NET AJAX script services and page methods understand and expect parameters serialized as JSON strings. These parameters are parsed out of the POST data and used as arguments to the method you’ve called.
3.  url: This contains the url of the page that will handle our AJAX request and provide the response. Notice here we have defined our url as Default.aspx/getItems. The first element before slash(/) contains the page name and the second item is the actual function name that will process the request in this case its getItems. 
4. data: This option defines the parameters that have to be passed (if any) to the function on the basis of which our request will be processed. In this case we are passing the selected value of the Category dropDown. Also its worth noting that the parameter name of this option should match the parameter of the function that we are going to call. In this case its 'category'
5. dataType: this option defines the type of Data that will be returned to us when the request is processed successfully. In this case its JSON (JavaScript Object Notation).
6. success: this option is an indication of a successful request processed and response. In this function we will define a function that will process the response (i.e. fill the Items dropDown). As you'll look at the C# code below, we are appending the items using a bar( | ), coz if there are multiple items we need to handle them in response. Here we are finally splitting the response string and finally handling each of them separately by storing them in the Items DropDown list.

Finally here is the C# Code Behind function that will handle my Request, Process it and Response back the output. Currently I have hard coded mr response. We can also make a database request and finally append each of the items using a bar ( | ) and response back the string (output).
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

[System.Web.Services.WebMethod]
public static string getItems(string category)
{
string strItems = "";
if (category == "Fruits")
{
strItems = "Apple|Orange|Pinapple|Grapes";
}
else if (category == "Vegetables")
{
strItems = "Tomato|Cauliflower|Brinjal|Potato";
}
else if (category == "Desserts")
{
strItems = "Cakes|Cookies|IceCreams|Pastries";
}
return strItems;
}
}

4 comments:

Imdad said...

thanks for posting the joke in my blog! Also, came to know about you and your skills....very late to notice your comment...regrets!

by-the-way, since ur a king in html...i need ur assistance!

imdad

AJ said...

Neat

Anonymous said...

thanks very easy to learn..

erectile dysfunction said...

Thank you for the good writeup. It in fact was a amusement account it. Look advanced to more added agreeable from you! However, how can we communicate?