Home > ASP.Net, Jquery > Fill DropdownList through JSON data using jQuery

Fill DropdownList through JSON data using jQuery


Hi all,

try this example to Fill DropdownList through JSON data using jQuery

1) Open VS2008 and create a new website and add new web page

2) From Toolbox drag Lable and DropdownList


<p>
 <asp:DropDownList ID="DropDownList1"runat="server"/>
 </p>
 <asp:Label ID="msg"runat="server"></asp:Label>

3) In Code behind add the following code :


[WebMethod]
public static List<Employee> fetchData()
 {
 return new List<Employee>()
 {
 new Employee{ Fullname="Aamir Hasan", ID=1},
 new Employee{ Fullname="Awais Ahmed", ID=2},
 new Employee{ Fullname="Mahwish Khan", ID=3},
 new Employee{ Fullname="Saba Khan", ID=4},
 new Employee{ Fullname="Hina Ahmed", ID=5},
 new Employee{ Fullname="Gill Gate", ID=6}
 };
 }
}

public class Employee
{
 public string Fullname { get; set; }
 public int ID { get; set; }
}

4) Now add this script to fill Dropdownlist


<script src="Scripts/jquery-1.4.1.js"type="text/javascript"></script>
 <script language="javascript">
 $.ajax({
 type: "POST",
 url: "Default.aspx/fetchData",
 data: "{}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (response) {
 var Dropdown = $('#<%=DropDownList1.ClientID %>');
 Dropdown.append(new Option("SELECT", 0));
 $.each(response.d, function (index, item) {
 Dropdown.append(new Option(item.Fullname, item.ID));
 });
 },
 error: function () {
 alert("Failed to load data");
 }
 });

$(document).ready(function () {
 var dropdown = $('#<%=DropDownList1.ClientID %>');
 dropdown.change(function () {
 $("#<%=msg.ClientID%>").text(dropdown.val());
 });
 });

 </script>

Now run your page

Hope this helps

Good Luck

 

Advertisements
Categories: ASP.Net, Jquery
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: