Wednesday, October 17, 2012

Asp.Net Bind Populate DropDownList With JQuery And XML

In this example i'm explaining How To Populate Or Bind DropDownList With JQuery And XML In Asp.Net.

bind populate dropdownlist with jquery and xml

Add jquery library reference in head section and place one dropdown on the page.

Add one list item with select as it's value.

   1:  <asp:DropDownList ID="DropDownList1" runat="server">
   2:  <asp:ListItem>Select</asp:ListItem>
   3:  </asp:DropDownList>
   4:   
   5:  <asp:Label ID="Label1" runat="server" Text=""/>


Following is the Cities.xml file i'm using to bind dropdownlist using jquery.
01<!--?xml version="1.0" encoding="utf-8" ?-->
02<cities>
03  <city>
04    <name>Mumbai</name>
05    <id>1</id>
06  </city>
07    <city>
08    <name>Delhi</name>
09      <id>2</id>
10  </city>
11  <city>
12    <name>Banglore</name>
13    <id>3</id>
14  </city>
15  <city>
16    <name>Chennai</name>
17    <id>4</id>
18  </city>
19</cities>

Add this script in head section of page.

01<script src="jquery-1.7.2.min.js" type="text/javascript"></script>  
02<script type="text/javascript">
03$(document).ready(function()
04{
05  $.ajax(
06  {
07    type: "GET",
08    url: "Cities.xml",
09    dataType: "xml",
10    success: function(xml)
11    {
12      var dropDown = $('#<%=DropDownList1.ClientID %>');
13      $(xml).find('City').each(function()
14      {
15        var name = $(this).find('name').text();
16        var id = $(this).find('id').text();
17        dropDown.append($("<option></option>").val(id).html(name));
18      });
19      dropDown.children(":first").text("--Select--").attr("selected", true);
20    }
21  });
22  $('#<%=DropDownList1.ClientID %>').change(function()
23  {
24  var ddl = $('#<%=DropDownList1.ClientID %>');
25  var selectedText = $('#<%=DropDownList1.ClientID %> option:selected').text();
26  var selectedValue = $('#<%=DropDownList1.ClientID %>').val();
27  document.getElementById('Label1').innerHTML = "You selected " + selectedText + " With id " + selectedValue;
28  });
29});
30</script>

Build and run the code.

No comments:

Post a Comment