Thursday, November 5, 2009

Cascading Dropdownlist using JQuery and WebService

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title></title>

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

  <script type="text/javascript">
      $().ready(function() {
          $.ajax({
              type: "POST",
              url: "WebService.asmx/GetStates",
              data: "{}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(msg) {
                  BindStateddl(msg.d)
              }
          });
          //Fetch related city
          $("#ddlStates").change(function() {
              var StateID = $("#ddlStates > option[@selected]").attr("value");
              $("#ddlCities").html("");
              $.ajax({
                  type: "POST",
                  url: "WebService.asmx/FindCityByID",
                  data: "{ID:'" + StateID + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(msg) {
                      BindCityddl(msg.d)
                  }
              });
          });
      });
      function BindStateddl(msg) {
          $.each(msg, function() {

              $("#ddlStates").append($("<option></option>").val(this['StateId']).html(this['Name']));

          });
      }
      function BindCityddl(msg) {
          $.each(msg, function() {

              $("#ddlCities").append($("<option></option>").val(this['CityID']).html(this['Name']));

          });
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <table>
          <tr>
              <td>
                  State
              </td>
              <td>
                  <asp:DropDownList ID="ddlStates" runat="server">
                      <asp:ListItem Value="0">Select</asp:ListItem>
                  </asp:DropDownList>
              </td>
          </tr>
          <tr>
              <td>
                  Cities
              </td>
              <td>
                  <select id="ddlCities" runat="server">
                  </select>
              </td>
          </tr>
      </table>
  </div>
  </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

  /// <summary>
  /// Filter city by StateID
  /// </summary>
  /// <param name="ID"></param>
  /// <returns></returns>
  [WebMethod]
  public List<Cities> FindCityByID(string ID)
  {
      return GetCities().FindAll(x => x.StateId == int.Parse(ID));

  }
  /// <summary>
  /// Return list of cities.
  /// </summary>
  /// <returns></returns>
  public List<Cities> GetCities()
  {
      List<Cities> cities = new List<Cities>()
          {
              new Cities{CityID=1,StateId=1,Name="Lucknow"},
              new Cities{CityID=2,StateId=1,Name="Allahabad"},
              new Cities{CityID=3,StateId=2,Name="Patiala"},
              new Cities{CityID=4,StateId=2,Name="Amritsar"},
              new Cities{CityID=5,StateId=3,Name="Shimla"},
         
          };
      return cities;
  }


  /// <summary>
  /// Return List of states
  /// </summary>
  /// <returns></returns>
  [WebMethod]
  public List<State> GetStates()
  {

      List<State> states = new List<State>()
          {
              new State{StateId=1,Name="UP"},
              new State{StateId=2,Name="Punjab"},
              new State{StateId=3,Name="Himachal"}
          };
      return states;

  }
  /// <summary>
  /// 
  /// </summary>
  public class State
  {
      public int StateId { get; set; }
      public string Name { get; set; }
  }
  /// <summary>
  /// 
  /// </summary>
  public class Cities
  {
      public int CityID { get; set; }
      public int StateId { get; set; }
      public string Name { get; set; }
  }

}

Download

4 comments :

  1. thanks for this post
    This what i want ...

    http://csharpektroncmssql.blogspot.com

    ReplyDelete
  2. ADD BUTTON CONTROL, DO POSTBACK AND YOUR CODE WILL CRASH

    ReplyDelete
  3. thanks nice and simple explaination
    Asif Iqbal
    dotnet-tricks.com

    ReplyDelete