Tuesday, October 8, 2013

jQuery Cascading Dropdown List in Asp.net with Example

WebForm4.aspx:-
---------------
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm4.aspx.cs" Inherits="WebApplication2.WebForm4" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#<%=ddlstate.ClientID %>').attr('disabled', 'disabled');
            $('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
            $('#<%=ddlstate.ClientID %>').append('<option selected="selected" value="0">Select State</option>');
            $('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
            $('#<%=ddlcountries.ClientID %>').change(function () {
                var country = $('#<%=ddlcountries.ClientID%>').val()
                $('#<%=ddlstate.ClientID %>').removeAttr("disabled");
                $('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
                $('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
                $.ajax({
                    type: "POST",
                    url: "WebForm4.aspx/BindStates",
                    data: "{'country':'" + country + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var j = jQuery.parseJSON(msg.d);
                        var options;
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
                        }
                        $('#<%=ddlstate.ClientID %>').html(options)
                    },
                    error: function (data) {
                        alert('Something Went Wrong ' + data)
                    }
                });
            });
            $('#<%=ddlstate.ClientID %>').change(function () {
                var stateid = $('#<%=ddlstate.ClientID%>').val()
                $('#<%=ddlcity.ClientID %>').removeAttr("disabled");
                $.ajax({
                    type: "POST",
                    url: "WebForm4.aspx/BindRegion",
                    data: "{'state':'" + stateid + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var j = jQuery.parseJSON(msg.d);
                        var options;
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
                        }
                        $('#<%=ddlcity.ClientID %>').html(options)
                    },
                    error: function (data) {
                        alert('Something Went Wrong')
                    }
                });
            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Country</td>
                    <td>
                        <asp:DropDownList ID="ddlcountries" runat="server"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>State</td>
                    <td>
                        <asp:DropDownList ID="ddlstate" runat="server"></asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td>Region</td>
                    <td>
                        <asp:DropDownList ID="ddlcity" runat="server"></asp:DropDownList>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>
WebForm4.aspx.cs:-
------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.Services;
using System.Web.UI.WebControls;

namespace WebApplication2
{
    public partial class WebForm4 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCountries();
            }
        }

        private void BindCountries()
        {
            DataTable dtName = new DataTable();

            //Add Columns to Table
            dtName.Columns.Add(new DataColumn("CountryName"));
            dtName.Columns.Add(new DataColumn("CountryID"));

            //Now Add Values
            dtName.Rows.Add("Countries1", "0");
            dtName.Rows.Add("Countries2", "1");
            dtName.Rows.Add("Countries3", "2");

            //At Last Bind datatable to dropdown.
            ddlcountries.DataSource = dtName;
            ddlcountries.DataTextField = dtName.Columns["CountryName"].ToString();
            ddlcountries.DataValueField = dtName.Columns["CountryID"].ToString();
            ddlcountries.DataBind();
        }

        [WebMethod]
        public static string BindStates(string country)
        {
            StringWriter builder = new StringWriter();

            DataTable dtStates = new DataTable();

            //Add Columns to Table
            dtStates.Columns.Add(new DataColumn("StateName"));
            dtStates.Columns.Add(new DataColumn("StateID"));

            //Now Add Values
            dtStates.Rows.Add("State1", "0");
            dtStates.Rows.Add("State2", "1");
            dtStates.Rows.Add("State3", "2");

            builder.WriteLine("[");
            if (dtStates.Rows.Count > 0)
            {
                builder.WriteLine("{\"optionDisplay\":\"Select State\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
                for (int i = 0; i <= dtStates.Rows.Count - 1; i++)
                {
                    builder.WriteLine("{\"optionDisplay\":\"" + dtStates.Rows[i]["StateName"] + "\",");
                    builder.WriteLine("\"optionValue\":\"" + dtStates.Rows[i]["StateID"] + "\"},");
                }
            }
            else
            {
                builder.WriteLine("{\"optionDisplay\":\"Select State\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
            }
            string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
            returnjson = returnjson + "]";
            return returnjson.Replace("\r", "").Replace("\n", "");
        }

        [WebMethod]
        public static string BindRegion(string state)
        {
            StringWriter builder = new StringWriter();

            DataTable dtRegion = new DataTable();

            //Add Columns to Table
            dtRegion.Columns.Add(new DataColumn("RegionName"));
            dtRegion.Columns.Add(new DataColumn("RegionID"));

            //Now Add Values
            dtRegion.Rows.Add("Region1", "0");
            dtRegion.Rows.Add("Region2", "1");
            dtRegion.Rows.Add("Region3", "2");

            builder.WriteLine("[");
            if (dtRegion.Rows.Count > 0)
            {
                builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
                for (int i = 0; i <= dtRegion.Rows.Count - 1; i++)
                {
                    builder.WriteLine("{\"optionDisplay\":\"" + dtRegion.Rows[i]["RegionName"] + "\",");
                    builder.WriteLine("\"optionValue\":\"" + dtRegion.Rows[i]["RegionID"] + "\"},");
                }
            }
            else
            {
                builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
                builder.WriteLine("\"optionValue\":\"0\"},");
            }
            string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
            returnjson = returnjson + "]";
            return returnjson.Replace("\r", "").Replace("\n", "");
        }
    }
}
Source:-
Thank You.

No comments:

Post a Comment

Featured Post

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management https://docs.microsoft.com/en-us/azure/api-management/api-...

Popular posts