How to Use JQuery $.ajax() with Asp.net Dropdown list onchange event.

How to Use JQuery $.ajax() (AJAX) with Asp.net Drop down list’s “onchange” event and pass selected value
as parameter.

To perform above you need Jquery library, click on downloads to see where you can get Jquery.

Following is the working example in which I am selecting a role from asp.net dropdown list and
for that role I am getting Descrition from database using Jquery Ajax call.

To complet above you need to follow the following steps.

1. Add Jquery reference to the page.

<head>
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.3.1.min.js"></script>
</head>

Scripts is the directory name for my project where I put all my Javascript.

jquery-1.3.1.min.js is the JQuery Library.

2. Create the required asp.net code in body section, Following is my asp.net code you create your own
as per your requirement.

<body>
<div>
<span>
Selct Role:
</span>
 
<span>
<asp:dropdownlist ID="ddlUserRoles" runat="server" DataValueField="RoleId" DataTextField="RoleName">
</asp:dropdownlist>
</span>
 
<span id="spanUserRoleDescription"></span>
 
 
</div>
 
</body>

3. Write Javascript Code, I’ve created a javascript function getRoleDescription()

<script language="javascript" type="text/javascript" >
 
function getRoleDescription()
{
 
var myval=$("#< %=ddlUserRoles.ClientID%>;").val();
 
$.ajax({
type:"POST",
url:"/Admin/SDUsers.aspx/GetUserRoleDescription",
data:"{userroleid:'"+myval+"'}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function(response)
{
$("#spanUserRoleDescription").text(response);
}
 
});
}
 
</script>

Explination:
var myval=$(“#< %=ddlUserRoles.ClientID%>;”).val()

myval is a local variable inside function which is storing asp.net dropdown list value.

Look at the val() function in Jquery which gives value of the selected item, its very
simple and gives you, what you need.

ClientID is passing the Clientside Id of drop downlist

“#” is used in Jquery to get the ID of any element syntax is $(“#ElementId”)
becuasee my dropdown is a asp.net server side control and is bound to database table
I am passing its client id between < %= %>.

In $ajax
type:”POST” action type we are doing on the page
url: is the path to the c# static method which is defined as [WebMethod] and will get Role description from database
data: takes parameters for the calling function, In my example I am calling method
GetUserRoleDescription which takes one paramter userroleid

Note that parameter name in server side method and here in data: must be same and we need
to write parameter:value in the $.ajax() method.

contentType:”application/json; charset=utf-8″ tO Use Jquery in asp.net we need to return
contents in Json format so we are defining content type as Json and characterset a utf-8

datatype:”json” data type would be Json too
on successfull ajax call we will write our results in the span whos id is spanUserRoleDescription
success:function(response)
{
$(“#spanUserRoleDescription”).text(response);
}

4. Write server side code I am using C# you can write in vb.net

using System.Web.Services ;// this is page direct required for [WebMethod]

/// <summary>
/// Gets the user role description for the selected user
/// </summary>
/// <param name="userroleid"/>user role
/// <returns>String:User role sescription</returns>
 
[WebMethod]
public static string GetUserRoleDescription(string userroleid)
{
UserRolesService userRolesSer = new UserRolesService();return ((UserRoles)userRolesSer.GetByUserRoleTypeId(new Guid(userroleid))).UserRoleTypeDescription;}

Above method is used by me to access my database for test purpose you can write above method as

[WebMethod]
public static string GetUserRoleDescription(string userroleid)
{ return "Hello World"; }

C# function must be a static function and its must be public and you must define it as [WebMethod]

As we need asp.net drop down list’s client side “onchange” event which is not available directly in asp.net code so we need to pass it from c#

4. On page load event add this line to call Javascript function .

ddlUserRoles.Attributes.Add("onchange","getRoleDescription()")

Tags: , , , , , , ,

7 Responses to “How to Use JQuery $.ajax() with Asp.net Dropdown list onchange event.”

  1. Iqbal Singh says:

    nice code ….thanks very much for this beautiful code.

  2. Shalini says:

    Looking very simple and easy to implement!!! Great!!

  3. junric px says:

    thanks, very nice……………….

  4. tushar patel says:

    my data r the insert then we have to the iQuery is a dropdowl list
    then we have the data r countable for daily….etc is a value
    asp.net

  5. enione says:

    There is small problem. E.g.: if you will try to get DropDownList.selectedIndex (or other information about selected item) from code-behind you probably will always get first item. Solution: can use Request.Form[DropDownList.UniqueID]. It will give you DropDownList.selectedValue and then search among items thatever you want.

  6. dieta dukan says:

    Pretty great post. I just stumbled upon your weblog and wished to mention that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing on your rss feed and I hope you write again very soon!