In ASP.NET, we may need to populate the dropdown list from the database using jQuery AJAX in a few situations when data is dynamic or dropdown is created based on some previous user input data, so in this article, I am going to explain how you can fetch database data dynamically and populate or fill it in your dropdown list using jQuery AJAX and JSON.

Let's create a new project ASP.NET Web-Forms project in your Visual Studio, by navigating to File->New->Project-> Select Web from left pane and ASP.NET web-application from the right pane, name your project and Click OK -> Select "Empty" template and click OK.

Now, suppose this is our database table and dummy data for which we want to generate the dropdown list

bind-dropdown-list-using-ajax-json-in-asp-net-web-forms

Here are the points which we need to follow

  • Use Jquery ajax function
  • Use [WebMethod] attribute on BindDropdownlist method.
  • BindDropdownlist method should be static.
  • Create a class Student and use it to store data into the list.
  • Use JavaScriptSerializer's Serialize method for returning data into JSON format.
  • Use $('#<%=DropDownList1.ClientID%>') for Asp.Net dropdownlist ID in JQuery.
  • Add namespace System.Data,System.Data.SqlClient,System.Web.Services and System.Web.Script.Serialization in your c# page

Now generate an Index.aspx page inside your Empty Project, and place the C# code as below to create web-method and fetch data from database in Student list

       [WebMethod]
        public static string BindDropdownlist()
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-1PM1CJ9\SQLEXPRESS2;Initial Catalog=Students;Integrated Security=True");

            DataTable dt = new DataTable();

            SqlDataAdapter da = new SqlDataAdapter("Select ID, Name from Student_details", con);

            con.Open();
            da.Fill(dt);
            con.Close();

            List<Student> liststudent = new List<Student>();



            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Student objst = new Student();
                    objst.ID = Convert.ToInt32(dt.Rows[i]["ID"]);
                    objst.Name = Convert.ToString(dt.Rows[i]["Name"]);
                    liststudent.Insert(i, objst);
                }



            }

            JavaScriptSerializer jscript = new JavaScriptSerializer();
            return jscript.Serialize(liststudent);
        }


        public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }

So your Complete Index.aspx.cs code will be as below

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace jQueryAJAXDDL
{
    public partial class Index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        //  Method for binding Dropdownlist

        [WebMethod]
        public static string BindDropdownlist()
        {
            SqlConnection con = new SqlConnection(@"Data Source=DESKTOP-1PM1CJ9\SQLEXPRESS2;Initial Catalog=Students;Integrated Security=True");

            DataTable dt = new DataTable();

            SqlDataAdapter da = new SqlDataAdapter("Select ID, Name from Student_details", con);

            con.Open();
            da.Fill(dt);
            con.Close();

            List<Student> liststudent = new List<Student>();



            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Student objst = new Student();
                    objst.ID = Convert.ToInt32(dt.Rows[i]["ID"]);
                    objst.Name = Convert.ToString(dt.Rows[i]["Name"]);
                    liststudent.Insert(i, objst);
                }



            }

            JavaScriptSerializer jscript = new JavaScriptSerializer();
            return jscript.Serialize(liststudent);
        }


        public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    }
}

Now in your Index.aspx create jQuery Ajax method to call the web method and return JSON, which we will loop to create/populate dropdown list values, or you can say using which we will populate dropdown list data.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="jQueryAJAXDDL.Index" %>

<!DOCTYPE html>
<html>

<head runat="server">

    <title>Bind Dropdownlist by Ajax json</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function () {

            $.ajax({

                type: "POST",
                url: "Index.aspx/BindDropdownlist",
                data: {},               
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    var jsdata = JSON.parse(data.d);
                    $.each(jsdata, function (key, value) {
                        $('#<%=DropDownList1.ClientID%>').append($("<option></option>").val(value.ID).html(value.Name));
                    });
                },
                error: function (data) {
                    alert("error found");
                }

            });

        });

    </script>

</head>

<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server" >
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

That's it, we are done, build and run it in the browser, you will get output as shown below in gif image.

dropdown-list-using-jquery-ajax-asp-net-min.gif

Feel free to comment or ask any questions related to this article.

You may also like to read:

C# Create OR Generate Word Document using DocX

Convert EPOC (Unix) time stamp to Datetime and Vice-Versa in C#