Cascading Dropdown list by HttpHandler in c# asp.net:
download source code:download
demo:
In my previous example I was explained how to make cascading dropdownlist by jquery .ajax() method.In this example i used HttpHandler class and jquery .getJSON() method to manipulate cascading dropdownlist. Before use this method we should know about this method and HttpHandler class.
jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
url : It's a string containing the URL to which the request is sent.
data: data is a map or string that is sent to the server with the request.
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.
Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is an object (map), it is converted to a string and url-encoded before it is appended to the URL.
Most implementations will specify a success handler.The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.The success callback function receives a "jqXHR" object(in jQuery 1.4, it received the XMLHttpRequest object).For more details visit jQuery's mother site.
An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser.For more details visit msdn.
Ok. Let's try to implement.At first we have registered jquery method in our .axpx file:
<script src="../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.selectboxes.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// register getJobstation function with first dropdown's change event
$('#ddlUnit').change(getJobstation);
$('#ddlJobStation').attr('disabled', true);
$('#ddlTeam').attr('disabled', true);
$('#ddlShift').attr('disabled', true);
});
</script>
Here I have registered all of the innitial event with dropdownlist. ddlUnit is the first dropdown list in my project.It's onChange event I have called getJobstation function and due to getJobstation function i have registred another function that depends on unit id with ddlJobstaion's onChange event.Here jquery.selectboxes.min.js has been used to remove unused values and text from dropdownlist.
Here the getJobstation function that is called due to unit dropdown onChange.
function getJobstation() {
var selectedUnit = $("#ddlUnit > option[@selected]").attr("value"); //-- Select Unit --
if (isNaN(selectedUnit) == false) {
if (selectedUnit > 0) {
$.getJSON('../DAL/HttpHandler/UnitwiseShiftInformation_Handler.ashx?serviceMethod=GetJobstationByUnit&intUnitId=' + selectedUnit, function (jobstationList) {
$('#ddlJobStation').attr('disabled', false).change(getTeamByUnitJobstation).removeOption(/./).addOption('0', '-- Select Jobstation --');
$('#ddlTeam').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Team --');
$('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');;
$.each(jobstationList, function () {
$("#ddlJobStation").append($("<option></option>").val(this['intJobstationId']).html(this['strJobStationName']));
});
});
}
}
else {
$('#ddlJobStation').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Jobstation --');
$('#ddlTeam').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Team --');
$('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');
$('#divDisplay').empty();
}
}
Here "UnitwiseShiftInformation_Handler.ashx" is our HttpHandler class. In the >getJSON url we called HttpHandllerClass with parameters, one is the method should called and unit id.
UnitwiseShiftInformation_Handler.ashx?serviceMethod=GetJobstationByUnit&intUnitId=' + selectedUnit
HttpHandler Class is given bellow:
public class UnitwiseShiftInformation_Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string serviceMethod = context.Request.QueryString["serviceMethod"];
UnitwiseShiftInformation_DAL objUnitwiseShiftInformation_DAL = new UnitwiseShiftInformation_DAL();
List<string[]> returnItemList = new List<string[]>();
StringBuilder strReturnItemList = new StringBuilder();
//Now generate JSON format data according to calling method
//{"d": [{ "feildName":"value" , "feildName":"value" },{ "feildName":"value" , "feildName":"value" }]}
if (serviceMethod == "GetJobstationByUnit"){
int intUnitId = Convert.ToInt32((context.Request.QueryString["intUnitId"].ToString() == null ? "0" : context.Request.QueryString["intUnitId"]));
returnItemList = objUnitwiseShiftInformation_DAL.GetJobstationByUnit(intUnitId);
#region create json data format, like {"d": [{ "intJobstationId":"value" , "strJobStationName":"value" },....]}
strReturnItemList = new StringBuilder();
strReturnItemList.Append("[");
for (int index = 0; index < returnItemList.Count; index++)
{
strReturnItemList.Append("{");
strReturnItemList.Append("\"intJobstationId\":\" " + returnItemList[index][0] + "\",");
strReturnItemList.Append("\"strJobStationName\":\" " + returnItemList[index][1] + "\"");
strReturnItemList.Append("},");
}
strReturnItemList.Append("]");
#endregion
}
else if (serviceMethod == "GetTeamByUnitJobstation")
{
int intUnitId = Convert.ToInt32((context.Request.QueryString["intUnitId"].ToString() == null ? "0" : context.Request.QueryString["intUnitId"]));
int intJobstationId = Convert.ToInt32((context.Request.QueryString["intJobstationId"] == null ? "0" : context.Request.QueryString["intJobstationId"]));
returnItemList = objUnitwiseShiftInformation_DAL.GetTeamByUnitJobstation(intUnitId, intJobstationId);
#region create json data format, like {"d": [{ "intTeamId":"value" , "strTeamName":"value" },....]}
strReturnItemList = new StringBuilder();
strReturnItemList.Append("[");
for (int index = 0; index < returnItemList.Count; index++)
{
strReturnItemList.Append("{");
strReturnItemList.Append("\"intTeamId\":\" " + returnItemList[index][0] + "\",");
strReturnItemList.Append("\"strTeamName\":\" " + returnItemList[index][1] + "\"");
strReturnItemList.Append("},");
}
strReturnItemList.Append("]");
#endregion
}
else if (serviceMethod == "GetShiftByUnitJobstationTeam")
{
int intUnitId = Convert.ToInt32((context.Request.QueryString["intUnitId"].ToString() == null ? "0" : context.Request.QueryString["intUnitId"]));
int intJobstationId = Convert.ToInt32((context.Request.QueryString["intJobstationId"] == null ? "0" : context.Request.QueryString["intJobstationId"]));
int intTeamId = Convert.ToInt32((context.Request.QueryString["intTeamId"] == null ? "0" : context.Request.QueryString["intTeamId"]));
returnItemList = objUnitwiseShiftInformation_DAL.GetShiftByUnitJobstationTeam(intUnitId, intJobstationId, intTeamId);
#region create json data ,format like {"d": [{ "intShiftId":"value" , "strShiftName":"value" },....]}
strReturnItemList = new StringBuilder();
strReturnItemList.Append("[");
for (int index = 0; index < returnItemList.Count; index++)
{
strReturnItemList.Append("{");
strReturnItemList.Append("\"intShiftId\":\" " + returnItemList[index][0] + "\",");
strReturnItemList.Append("\"strShiftName\":\" " + returnItemList[index][1] + "\"");
strReturnItemList.Append("},");
}
strReturnItemList.Append("]");
#endregion
}
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Write(strReturnItemList.ToString());
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Now DAL Class is given bellow where original method is stated and called by HttpHandlerClass.
public class UnitwiseShiftInformation_DAL
{
DataTable odtTeamInformation = new DataTable();
public UnitwiseShiftInformation_DAL()
{
odtTeamInformation = new DataTable();
DataSet ods = new DataSet("odtTeamInformation");
ods.ReadXml(HttpContext.Current.Server.MapPath("~/DAL/Data/UnitWiseShiftInfo.xml")); //load xml as dataSet
odtTeamInformation = ods.Tables[0];
}
public DataTable GetAllUnit()
{
var unitList = (from items in odtTeamInformation.AsEnumerable()
select new
{
intUnitID = items.Field<string>("intUnitID"),
strUnit = items.Field<string>("strUnit")
}).Distinct();
DataTable odtUnit = new DataTable();
odtUnit.Columns.Add("intUnitID", typeof(int));
odtUnit.Columns.Add("strUnit", typeof(string));
foreach (var item in unitList)
{ odtUnit.Rows.Add(item.intUnitID, item.strUnit); }
return odtUnit;
}
public List<string[]> GetJobstationByUnit(int intUnitId)
{
List<string[]> jobstationList = new List<string[]>();
var query = (from items in odtTeamInformation.AsEnumerable()
where items.Field<string>("intUnitID") == intUnitId.ToString()
select new
{
intJobstationId = items.Field<string>("intEmployeeJobStationId"),
strJobStationName = items.Field<string>("strJobStationName")
}).Distinct();
foreach (var item in query)
{
jobstationList.Add(new string[2] { item.intJobstationId.ToString(), item.strJobStationName });
}
return jobstationList;
}
public List<string[]> GetTeamByUnitJobstation(int intUnitId, int intJobstationId)
{
List<string[]> teamList = new List<string[]>();
var query = (from items in odtTeamInformation.AsEnumerable()
where (items.Field<string>("intUnitID") == intUnitId.ToString() && items.Field<string>("intEmployeeJobStationId") == intJobstationId.ToString())
select new
{
intTeamId = items.Field<string>("intTeamId"),
strTeamName = items.Field<string>("strTeamName")
}).Distinct();
foreach (var item in query)
{
teamList.Add(new string[2] { item.intTeamId.ToString(), item.strTeamName });
}
return teamList;
}
public List<string[]> GetShiftByUnitJobstationTeam(int intUnitId, int intJobstationId, int intTeamId)
{
List<string[]> shiftList = new List<string[]>();
var query = (from items in odtTeamInformation.AsEnumerable()
where (items.Field<string >("intUnitID") == intUnitId.ToString() && items.Field<string >("intEmployeeJobStationId") == intJobstationId.ToString() && items.Field<string>("intTeamId") == intTeamId.ToString())
select new
{
intShiftId = items.Field<string>("intShiftId"),
strShiftName = items.Field<string>("strShiftName")
}).Distinct();
foreach (var item in query)
{
shiftList.Add(new string[2] { item.intShiftId.ToString(), item.strShiftName });
}
return shiftList;
}
}
.aspx code is given bellow:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CascadingDropdownListByHttpHandler.aspx.cs"
Inherits="CascadingDropdownByHttpHandler.UI.CascadingDropdownListByHttpHandler"
EnableEventValidation="false" %>
<!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 id="Head1" runat="server">
<title>Daily Shift Attendance</title>
<link href="../Styles/Lstyle.css" rel="stylesheet" type="text/css" />
<script src="../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.selectboxes.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#ddlUnit').change(getJobstation);
$('#ddlJobStation').attr('disabled', true);
$('#ddlTeam').attr('disabled', true);
$('#ddlShift').attr('disabled', true);
});
function getJobstation() {
var selectedUnit = $("#ddlUnit > option[@selected]").attr("value"); //-- Select Unit --
if (isNaN(selectedUnit) == false) {
if (selectedUnit > 0) {
$.getJSON('../DAL/HttpHandler/UnitwiseShiftInformation_Handler.ashx?serviceMethod=GetJobstationByUnit&intUnitId=' + selectedUnit, function (jobstationList) {
$('#ddlJobStation').attr('disabled', false).change(getTeamByUnitJobstation).removeOption(/./).addOption('0', '-- Select Jobstation --');
$('#ddlTeam').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Team --');
$('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');;
$.each(jobstationList, function () {
$("#ddlJobStation").append($("<option></option>").val(this['intJobstationId']).html(this['strJobStationName']));
});
});
}
}
else {
$('#ddlJobStation').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Jobstation --');
$('#ddlTeam').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Team --');
$('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');
$('#divDisplay').empty();
}
}
function getTeamByUnitJobstation() {
var selectedJobstation = $("#ddlJobStation > option[@selected]").attr("value");
var selectedUnit = $("#ddlUnit > option[@selected]").attr("value");
if (selectedJobstation > 0) {
$.getJSON('../DAL/HttpHandler/UnitwiseShiftInformation_Handler.ashx?serviceMethod=GetTeamByUnitJobstation&intUnitId=' + selectedUnit + '&intJobstationId=' + selectedJobstation, function (teamInfoList) {
$('#ddlTeam').attr('disabled', false).change(getShiftByUnitJobstationTeam).removeOption(/./).addOption('0', '-- Select Team --');
$('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');
$.each(teamInfoList, function () {
$("#ddlTeam").append($("<option></option>").val(this['intTeamId']).html(this['strTeamName']));
});
});
}
else {
$('#ddlTeam').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Team --');
$('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');
$('#divDisplay').empty();
}
}
function getShiftByUnitJobstationTeam() {
var selectedJobstation = $("#ddlJobStation > option[@selected]").attr("value");
var selectedUnit = $("#ddlUnit > option[@selected]").attr("value");
var selectedTeam = $("#ddlTeam > option[@selected]").attr("value");
if (selectedTeam > 0) {
$.getJSON('../DAL/HttpHandler/UnitwiseShiftInformation_Handler.ashx?serviceMethod=GetShiftByUnitJobstationTeam&intUnitId=' + selectedUnit + '&intJobstationId=' + selectedJobstation + '&intTeamId=' + selectedTeam, function (shiftInfoList) {
$('#ddlShift').attr('disabled', false).change(finallySelectedValues).removeOption(/./).addOption('0', '-- Select Shift --');
$.each(shiftInfoList, function () {
$("#ddlShift").append($("<option></option>").val(this['intShiftId']).html(this['strShiftName']));
});
});
}
else {
$('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');
$('#divDisplay').empty();
}
}
function finallySelectedValues() {
$('#divDisplay').empty();
$('#divDisplay').append('<p><strong>Your selected values are <br />Selected Unit:' + $("#ddlUnit > option[@selected]").attr("text") + '<br />Selected Jobstation: ' +
$("#ddlJobStation > option[@selected]").attr("text") + '</strong><br /><strong>Selected Team: ' +
$("#ddlTeam > option[@selected]").attr("text") + '</strong><br /><strong>Selected Shift: ' +
$("#ddlShift > option[@selected]").attr("text") + '</strong></p>');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Unit" CssClass="label"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlUnit" runat="server" Width="150px" DataSourceID="odsUnit"
DataTextField="strUnit" DataValueField="intUnitID">
</asp:DropDownList>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="Job Station" CssClass="label"></asp:Label>
</td>
<td>
<select id="ddlJobStation" runat="server" style="width: 150px; text-align: center">
</select>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<asp:Label ID="Label3" runat="server" Text="Team" CssClass="label"></asp:Label>
</td>
<td>
<select id="ddlTeam" runat="server" style="width: 150px; text-align: center">
</select>
</td>
<td></td>
<td></td>
</tr>
<tr>
<td>
<asp:Label ID="Label5" runat="server" CssClass="label" Text="Shift"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlShift" runat="server" Width="150px" DataTextField="Text"
DataValueField="Value">
</asp:DropDownList>
</td>
<td></td>
<td></td>
</tr>
</table>
<table>
<tr>
<td>
<asp:ObjectDataSource ID="odsUnit" runat="server" SelectMethod="GetAllUnit" TypeName="CascadingDropdownByHttpHandler.DAL.Gateway.UnitwiseShiftInformation_DAL"
OldValuesParameterFormatString="original_{0}"></asp:ObjectDataSource>
</td>
<td></td>
<td></td>
</tr>
</table>
</div>
<table>
<tr>
<td style="width: 100px"></td>
<td>
<div id="divDisplay">
</div>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
It's better to download source code and then try to implement.
thank you.
No comments:
Post a Comment
Thanks for your comments