How to bind data in Dropdownlist in asp.net using JQuery Ajax and Web method.

Introduction :

Hi, Here i will explain you how to bind the value into Dropdownlist Using web-method by JQuery Ajax and JSON. In the below Example i will explain binding dropdownlist by selecting the values in other dropdownlist.

This is bit difficult compare to C# binding. but it avoids page loads, and Execution time is Fast.

steps to Remember :

1) Your web method function Should be Static. and returns as a List.
2) Your Parameter name which you are sending Should be Same in both JQuery and C# (Exp: StuID)
3) Here 'StudentRegistration' is the column name of database to bind to DropDown.
4) Should Create Property class to pass Data from C# to Jquery-Ajax as Json.

Asp.Net Code :


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Fourth Bottle</title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
   <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>


    <script type="text/javascript">
   function Load_Regno() {

       var StuID = document.getElementById('DropDownList1').value;
      $.ajax(
        {
           type: "POST",
           contentType: "application/json;charset=utf-8",
           url: "drop.aspx/Loadetails",
           data: JSON.stringify({ StuID: StuID }),
           dataType: "json",
           success: function (data) {
             var theDropDown = document.getElementById("DropDownList2");
             theDropDown.length = 0;
             $.each(data.d, function (key, value) {
             $("#DropDownList2").append($("<option>                    </option>").val(value.Regno).html(value.Regno));
                });
            },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
              if (XMLHttpRequest.status == 0) {
                       alert(' Check Your Network.');
              } else if (XMLHttpRequest.status == 404) {
                       alert('Requested URL not found.');
              } else if (XMLHttpRequest.status == 500) {
                       alert('Internel Server Error.');
               } else {
             alert('Unknow Error.\n' + XMLHttpRequest.responseText);
                    }
              }
        });

            return false;
   }
     </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" AutoPostBack="false" runat="server" onchange="return Load_Regno();">
        </asp:DropDownList>
        <br />
        <asp:DropDownList ID="DropDownList2" runat="server" >
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>


 C# Code :    

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Runtime.Serialization;


namespace GridLoad
{
    public partial class drop : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string Conec = ConfigurationManager.ConnectionStrings["Student"].ConnectionString;
            SqlConnection con = new SqlConnection(Conec);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select StudentID from StudentMarks", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DropDownList1.DataSource = dt;
            DropDownList1.DataValueField = dt.Columns["StudentID"].ColumnName.ToString();
            DropDownList1.DataTextField = dt.Columns["StudentID"].ColumnName.ToString();
            DropDownList1.DataBind();

        }

        [System.Web.Services.WebMethod]
        public static RegDetails[] Loadetails(string StuID)
        {
            string Conec = ConfigurationManager.ConnectionStrings["Student"].ConnectionString;
            SqlConnection con = new SqlConnection(Conec);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("select ' select' StudentRegistration union select StudentRegistration from StuRegno where StudentID='" + StuID + "'", con);
            DataTable st = new DataTable();
            da.Fill(st);
            List<RegDetails> details = new List<RegDetails>();
            foreach (DataRow dtrow in st.Rows)
            {
                RegDetails obj = new RegDetails();
                obj.Regno = dtrow["StudentRegistration"].ToString();
                details.Add(obj);
            }
            JavaScriptSerializer ser = new JavaScriptSerializer();
            return details.ToArray();
        }

        public class RegDetails
        {
            public string Regno { get; set; }
        }

        public class StudentDetails
        {
            public string StudentName { get; set; }
            public string Gender { get; set; }
            public string StudentID { get; set; }

        }
    }
}