Monday, December 19, 2011

Cascading Dropdown lists in asp.net

we will used the seletedIndex change event  when you working with populate dropdown list using another dropdown list selection   in asp.net.By using this Event the page loading  is occur .so every time page loading process gives the burden to application performance.For this we can use the Jquery to avoid the page loading concept.I will shown how to populate the drop down list based on selection of another drop down list.Here i have taken two drop down lists which are ddlattdoctor and ddlattdoctor.
var pageUrl = '<%=ResolveUrl("~/IPRegistration.aspx")%>'
function PopulateDepartments() {
 $("#<%=ddlattdoctor.ClientID%>").attr("disabled", "disabled");
if ($('#<%=ddlattdept.ClientID%>').val() == "0") {
   $('#<%=ddlattdoctor.ClientID %>').empty().append('No Doctor');
        }
        else {

   $('#<%=ddlattdoctor.ClientID %>').empty().append('Loading...');
              $.ajax({
                type: "POST",
                url: pageUrl + '/PopulateDoctors',
                data: '{deptid: ' + $('#<%=ddlattdept.ClientID%>').val() + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnDoctorsPopulated,
                failure: function(response) {
                    alert(response.d);
                }
            });
        }
    }

    function OnDoctorsPopulated(response) {
        PopulateControl(response.d, $("#<%=ddlattdoctor.ClientID %>"));
    }


//this is for populate doctors dropdwon list
    function PopulateControl(list, control) {
        if (list.length > 0) {
            control.removeAttr("disabled");
            control.empty().append('(Please Select)');
            $.each(list, function() {
                control.append($("").val(this['Value']).html(this['Text']));
            });
        }
        else {

            control.removeAttr("disabled");
            control.empty().append('(No Doctor)');
           // control.empty().append('Not available');
        }
    }

Here i have created a static web method Then the server side process will take the Asp.net ajax.This web method is called as ASP.NET Ajax page method. PopulateDoctors() is return the list of items which are bind to drop down using jquery
[System.Web.Services.WebMethod]

public static ArrayList PopulateDoctors(int deptid)
 {
  SqlConnection con=newSqlConnection(ConfigurationManager.AppSettings["connection"].ToString());
  ArrayList list = new ArrayList();
  string strQuery = "select docname,docid from docmaster where deptid='" + deptid + "'";
  SqlCommand cmd = new SqlCommand(strQuery, con);
  con.Open();
  SqlDataReader sdr = cmd.ExecuteReader();
  while (sdr.Read())
   {
   list.Add(new ListItem(
   sdr["docname"].ToString(),
   sdr["docid"].ToString()
   ));
  }
   con.Close();
   return list;
}

No comments:

Bel