Normally some folks posting the Question "How to get the Second Dropdown fill based on the first dropdown selection?".The processing of filling the second dropdown based on the first dropdown selection is called "Cascading Dropdown or Filtered Dropdown".Actually the data source i have used is XML file which contains the Country and State.In the source code this XML file is also given please check once you download the source code.
Cascading dropdown can be done in many ways out of which i have chosen this using jQuery.I have taken the common example of Country and States .I have taken two Composite types as "Country" and "State" which contains properties as ID ,Name.I have given the structure also.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CascadingExample
{
public class Country
{
public string CountryName { get; set; }
public int CountryID { get; set; }
public List FetchStates(string countryName)
{
return new List { };
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CascadingExample
{
public class State
{
public State()
{
//To Do
}
public int StateID { get; set; }
public int CountryID { get; set; }
public string StateName { get; set; }
}
}
I have degined a seperate class for fetching data from the data source (XML file) based on the filtering.The name of the classs is given as the"DataManager".
To present this example in a beautiful way i desgined a screen as shown below
I have fetched the Countries list from the XML file in the Page_load of the Page and the method("FetchCountries") in the DataManager class.
public List FetchCountries()
{
List lstCountry = new List();
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlPath);
XmlElement root = xDoc.DocumentElement;
XmlNodeList nodeList = root.GetElementsByTagName("country");
for (int i = 0; i < nodeList.Count; i++)
{
String countryName = String.Empty;
countryName = nodeList[i].Attributes["name"].Value;
lstCountry.Add(new Country { CountryID = i, CountryName = countryName });
}
return lstCountry;
}
The HTML design of the CascadingExample.aspx is given below
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CascadingDropDown.aspx.cs"
Inherits="CascadingExample.CascadingDropDown" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cascading DropDownLists With ASP.NET and jQuerytitle>
<style type="text/css">
.ddl_style
{
text-align: justify;
font-family: Verdana;
}
.para_Style
{
text-align: justify;
}
style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js">script>
<script type="text/javascript">
$(document).ready(function () {
var ddl = $("select[name$=ddlCountries]");
var ddlState = $("select[name$=ddlState]");
ddl.focus();
ddl.bind("change keyup", function () {
if ($(this).val() != "-1") {
$('p[class$="para_Style"]')[0].innerText = "";
loadStates($("select[name$=ddlCountries] option:selected").val(), $("select[name$=ddlCountries] option:selected").text());
ddlState.fadeIn("slow");
} else {
ddlState.fadeOut("slow");
}
});
});
function loadStates(selectedIndex, selectedText) {
$.ajax({
type: "POST",
url: "CascadingDropDown.aspx/FetchStates",
data: "{countryID:" + parseInt(selectedIndex) + ",countryName:'" + selectedText + "'}",
contentType: "application/json;char-set=utf-8",
dataType: "json",
async: true,
success: function Success(data) {
printStates(data.d);
selectedIndex = 0;
selectedText = '';
}
});
}
function printStates(data) {
$("select[name*=ddlState]>option").remove();
$("select[name*=ddlState]").append($("<option>option>").val(-1).html("(Please Select)"));
$('p[class$="para_Style"]').append("You have Selected <b> " + $("select[name$=ddlCountries] option:selected").text() + "b><br>State List is given below:<br>");
for (var i = 0; i < data.length; i++) {
$("select[name*=ddlState]").append($("<option>option>").val(data[i].StateID).html(data[i].StateName));
$('p[class$="para_Style"]').append(data[i].StateName + "<br>");
}
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="font-family: Verdana; text-align: left; font-size: medium; color: Green">
An Example to show Cascading Dropdown in Asp.Net using jQuery
h2>
<br />
<table style="font-family: Times New Roman Baltic; text-align: left; font-size: medium;
color: Red">
<tr>
<td>
<label>
Select Countrylabel><br />
td>
<td>
<asp:DropDownList ID="ddlCountries" runat="server" AppendDataBoundItems="true" CssClass="ddl_style">
<asp:ListItem Text="(Please Select)" Value="-1" Selected="True" />
asp:DropDownList>
td>
tr>
<br />
<tr>
<td>
<label>
Select Statelabel><br />
td>
<td>
<asp:DropDownList ID="ddlState" runat="server" CssClass="ddl_style" AppendDataBoundItems="true">
asp:DropDownList>
td>
tr>
table>
<p class="para_Style">
p>
div>
form>
body>
html>
In the Cascading Example i have designed a WebMethod and called using jQuery AJAX POST .
[WebMethod]
public static List FetchStates(int countryID, string countryName)
{
DataManager objDataManager = new DataManager();
List stateObj = new List();
stateObj=objDataManager.FetchState(new Country { CountryID = countryID, CountryName = countryName });
return stateObj;
}
When we run the page we will get the output as like this
To better understand this concept you need to analyse in the HTML watcher tools.The best tool what i can say is FireFox add on FireBug.If you dont have the firefox you need to download here(FireFox) and download the firebug add on here(FireBug).Now follow the steps given below
1. Click on the Firebug which will open in the bottom.
2. Now go to the "Net" tab where you will have different tabs like Header,Response,Post,JSON.
3. Now select the country in the first dropdown.
4. In the Net tab you can see in the POST tab you can see the method name as "FetchStates" which takes two input parameters as countryID and countryName.
5. We can see clearly the reposnse we got in the "Response" tab .
You can see in the below image
This is how we can do the cascading dropdown in ASP.NET using jQuery.
Happy Coding :-)
Cascading dropdown can be done in many ways out of which i have chosen this using jQuery.I have taken the common example of Country and States .I have taken two Composite types as "Country" and "State" which contains properties as ID ,Name.I have given the structure also.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CascadingExample
{
public class Country
{
public string CountryName { get; set; }
public int CountryID { get; set; }
public List
{
return new List
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CascadingExample
{
public class State
{
public State()
{
//To Do
}
public int StateID { get; set; }
public int CountryID { get; set; }
public string StateName { get; set; }
}
}
I have degined a seperate class for fetching data from the data source (XML file) based on the filtering.The name of the classs is given as the"DataManager".
To present this example in a beautiful way i desgined a screen as shown below
I have fetched the Countries list from the XML file in the Page_load of the Page and the method("FetchCountries") in the DataManager class.
public List
{
List
XmlDocument xDoc = new XmlDocument();
xDoc.Load(xmlPath);
XmlElement root = xDoc.DocumentElement;
XmlNodeList nodeList = root.GetElementsByTagName("country");
for (int i = 0; i < nodeList.Count; i++)
{
String countryName = String.Empty;
countryName = nodeList[i].Attributes["name"].Value;
lstCountry.Add(new Country { CountryID = i, CountryName = countryName });
}
return lstCountry;
}
The HTML design of the CascadingExample.aspx is given below
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CascadingDropDown.aspx.cs"
Inherits="CascadingExample.CascadingDropDown" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Cascading DropDownLists With ASP.NET and jQuerytitle>
<style type="text/css">
.ddl_style
{
text-align: justify;
font-family: Verdana;
}
.para_Style
{
text-align: justify;
}
style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.1.js">script>
<script type="text/javascript">
$(document).ready(function () {
var ddl = $("select[name$=ddlCountries]");
var ddlState = $("select[name$=ddlState]");
ddl.focus();
ddl.bind("change keyup", function () {
if ($(this).val() != "-1") {
$('p[class$="para_Style"]')[0].innerText = "";
loadStates($("select[name$=ddlCountries] option:selected").val(), $("select[name$=ddlCountries] option:selected").text());
ddlState.fadeIn("slow");
} else {
ddlState.fadeOut("slow");
}
});
});
function loadStates(selectedIndex, selectedText) {
$.ajax({
type: "POST",
url: "CascadingDropDown.aspx/FetchStates",
data: "{countryID:" + parseInt(selectedIndex) + ",countryName:'" + selectedText + "'}",
contentType: "application/json;char-set=utf-8",
dataType: "json",
async: true,
success: function Success(data) {
printStates(data.d);
selectedIndex = 0;
selectedText = '';
}
});
}
function printStates(data) {
$("select[name*=ddlState]>option").remove();
$("select[name*=ddlState]").append($("<option>option>").val(-1).html("(Please Select)"));
$('p[class$="para_Style"]').append("You have Selected <b> " + $("select[name$=ddlCountries] option:selected").text() + "b><br>State List is given below:<br>");
for (var i = 0; i < data.length; i++) {
$("select[name*=ddlState]").append($("<option>option>").val(data[i].StateID).html(data[i].StateName));
$('p[class$="para_Style"]').append(data[i].StateName + "<br>");
}
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="font-family: Verdana; text-align: left; font-size: medium; color: Green">
An Example to show Cascading Dropdown in Asp.Net using jQuery
h2>
<br />
<table style="font-family: Times New Roman Baltic; text-align: left; font-size: medium;
color: Red">
<tr>
<td>
<label>
Select Countrylabel><br />
td>
<td>
<asp:DropDownList ID="ddlCountries" runat="server" AppendDataBoundItems="true" CssClass="ddl_style">
<asp:ListItem Text="(Please Select)" Value="-1" Selected="True" />
asp:DropDownList>
td>
tr>
<br />
<tr>
<td>
<label>
Select Statelabel><br />
td>
<td>
<asp:DropDownList ID="ddlState" runat="server" CssClass="ddl_style" AppendDataBoundItems="true">
asp:DropDownList>
td>
tr>
table>
<p class="para_Style">
p>
div>
form>
body>
html>
In the Cascading Example i have designed a WebMethod and called using jQuery AJAX POST .
[WebMethod]
public static List
{
DataManager objDataManager = new DataManager();
List
stateObj=objDataManager.FetchState(new Country { CountryID = countryID, CountryName = countryName });
return stateObj;
}
When we run the page we will get the output as like this
To better understand this concept you need to analyse in the HTML watcher tools.The best tool what i can say is FireFox add on FireBug.If you dont have the firefox you need to download here(FireFox) and download the firebug add on here(FireBug).Now follow the steps given below
1. Click on the Firebug which will open in the bottom.
2. Now go to the "Net" tab where you will have different tabs like Header,Response,Post,JSON.
3. Now select the country in the first dropdown.
4. In the Net tab you can see in the POST tab you can see the method name as "FetchStates" which takes two input parameters as countryID and countryName.
5. We can see clearly the reposnse we got in the "Response" tab .
You can see in the below image
This is how we can do the cascading dropdown in ASP.NET using jQuery.
Happy Coding :-)
No comments:
Post a Comment