Monday, February 13, 2012

Cascading dropdownlist in Asp.Net using jQuery




*******************************************************************************

<%@ 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>Cascading dropdownlist in Asp.Net</title>

    <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>
   <!--downloadable free library from http://jqueryui.com/-->

    <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;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

********************************************************************************

/*Add new item WebService.asmx in your application*/

using System.Collections.Generic;
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;

    }

    public class State
    {
        public int StateId { get; set; }
        public string Name { get; set; }
    }

    public class Cities
    {
        public int CityID { get; set; }
        public int StateId { get; set; }
        public string Name { get; set; }
    }

}


Post a Comment