yeasir007

Friday, November 23, 2012

Cascading dropdownlist using jquery in asp.net page


Cascading dropdownlist using jquery in asp.net page:

download source code : download source code
demo




For data handling from server side here i used jquery .ajax method.method structure is given bellow:
$.ajax({
  type: "POST",
  url: "Service Url/Service method",
  data: "{Parameter}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(response) {
      //on success write your own code 
     });
  },
  failure: function(msg) {
    //on failure 
  }                                                                             });  

type: The type of request to make ("POST" or "GET"),default is "GET”.Other HTTP request methods,such as    "PUT" and "DELETE" can also be used here, but they are not supported by all browsers.
url: It's a string that contain url to which request is sent.
dataData to be sent to the server, works like a parameter. It is converted to a query string, if not already a string.
contentType: When sending data to the server, use this content type. Default is "application/x-www-forn-urlencoded;charset=UTF-8",which is the fine for the most cases. If you explicitly pass in a content type to $.ajax(),then it will always be sent to the server(even if no data is sent).If no charset is specified, data will be transmitted to the server using the server's default charser.you must decode this appropriately on the server side.
dataType
Default: Intelligent Guess (xmljsonscript, or html).
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
Ø "xml": Returns a XML document that can be processed via jQuery.
Ø "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
Ø "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to trueNote: This will turn POSTs into GETs for remote-domain requests.
Ø "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
Ø "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
Ø "text": A plain text string.
Ø multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.


for more details about $.ajax() method visit Query.ajax.
  

Here  i will be collect shift information which will be filtered by unit, job-station and team type.In this example I used xml database for simplification,you can collect data from database.
First Create a web service named UnitwiseShiftInformation_Service,which method will be called by .ajax() method.This web service will provide some web method that will be called by dependent drop-down list based on demand.  

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]
public class UnitwiseShiftInformation_Service :WebService
{
DataTable odtTeamInformation = new DataTable();
public UnitwiseShiftInformation_Service()
{
   odtTeamInformation = new DataTable();
   DataSet ods = new DataSet("odtTeamInformation");                              //here i used xml data. you can retrieve data from database   
   ods.ReadXml(HttpContext.Current.Server.MapPath("~/DAL/Data/UnitWiseShiftInfo.xml"));
    odtTeamInformation = ods.Tables[0];
  }
[WebMethod]
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;
}
[WebMethod]
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;
}
[WebMethod]
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;
}
[WebMethod]
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, item.strShiftName });
    }

    return shiftList;
}


.aspx code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CascadingDropdownByJequery.aspx.cs"
Inherits="CascadingDropdownByJquery.UI.CascadingDropdownByJequery" %>

 <!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.min.js" type="text/javascript"></script>
 <script src="../Scripts/jquery.selectboxes.min.js" type="text/javascript"></script>
 <link href="../Styles/Lstyle.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript">
    $(function () {
        $('#ddlUnit').change(getJobstation);
        $('#ddlJobStation').attr('disabled', true);
        $('#ddlTeam').attr('disabled', true);
        $('#ddlShift').attr('disabled', true);
    });


  function getJobstation() {

  var selectedValue = $("#ddlUnit > option[@selected]").attr("value");
  if (selectedValue > 0) {
   $.ajax({
    type: "POST",
    url: "../DAL/Webservices/UnitwiseShiftInformation_Service.asmx/                        GetJobstationByUnit",
    data: "{intUnitId: '" + $('#ddlUnit').val() + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
    var jobstation = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
    $('#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 --');

    for (var i = 0; i < jobstation.length; i++) {
         var val = jobstation[i][0];
         var text = jobstation[i][1];
         $('#ddlJobStation').addOption(val, text, false);
         }
    },
    failure: function (msg) {
                    alert(msg);
    }
   });
   }
   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 selectedValue = $("#ddlJobStation > option[@selected]").attr("value");
        if (selectedValue > 0) {
            $.ajax({
                type: "POST",
                url: "../DAL/Webservices/UnitwiseShiftInformation_Service.asmx/GetTeamByUnitJobstation",
                data: "{intUnitId: '" + $('#ddlUnit').val() + "', intJobstationId: '" + $('#ddlJobStation').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var team = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                    $('#ddlTeam').attr('disabled', false).change(getShiftByUnitJobstationTeam).removeOption(/./).addOption('0', '-- Select Team --');
                    $('#ddlShift').attr('disabled', true).change().removeOption(/./).addOption('0', '-- Select Shift --');

                    for (var i = 0; i < team.length; i++) {
                        var val = team[i][0];
                        var text = team[i][1];
                        $('#ddlTeam').addOption(val, text, false);
                    }
                },

                failure: function (msg) {
                    alert(msg);
                }
            });
        }
        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 selectedValue = $("#ddlTeam > option[@selected]").attr("value");
        if (selectedValue > 0) {
            $.ajax({
                type: "POST",
                url: "../DAL/Webservices/UnitwiseShiftInformation_Service.asmx/GetShiftByUnitJobstationTeam",
                data: "{intUnitId: '" + $('#ddlUnit').val() + "', " +
                  "intJobstationId: '" + $('#ddlJobStation').val() + "', " +
                  "intTeamId: '" + $('#ddlTeam').val() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var shift = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
                    $('#ddlShift').attr('disabled', false).change(finallySelectedValues).removeOption(/./).addOption('0', '-- Select Shift --');

                    for (var i = 0; i < shift.length; i++) {
                        var val = shift[i][0];
                        var text = shift[i][1];
                        $('#ddlShift').addOption(val, text, false);
                    }
                },

                failure: function (msg) {
                    alert(msg);
                }
            });
        }
        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.Webservice.UnitwiseShiftInformation_Service"
                            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>

.cs file
 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                ddlUnit.DataBind();
                ddlUnit.Items.Insert(0, "-- Select Unit --");
            }
            catch { }
        }
    }




No comments:

Post a Comment

Thanks for your comments