Introduction
In this article, I will discuss how to bind a select option on drop-down using pure JavaScript. Client-side binding is faster than that of the server-side. So, I need to bind the select option or drop-down using JavaScript.
Example
To achieve my goal, I will present a demo here. In the below demo, I will bind the student names in the dropdown.
Client-side code
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BindDropDown.aspx.cs" Inherits="XMLWrite.BindDropDown" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <script type="text/javascript">
- var ddlStudents;
- function GetStudentDetails() {
- ddlStudents = document.getElementById("<%=ddlStudents.ClientID %>");
- PageMethods.GetStudentDetails(OnSuccess);
- }
- window.onload = GetStudentDetails;
-
- function OnSuccess(response) {
- ddlStudents.options.length = 0;
- AddOption("Please select", "0");
- for (var i in response) {
- AddOption(response[i].Name, response[i].Id);
- }
- }
- function AddOption(text, value) {
- var option = document.createElement('option');
- option.value = value;
- option.innerHTML = text;
- ddlStudents.options.add(option);
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
- </asp:ScriptManager>
- <div>
- <asp:DropDownList ID="ddlStudents" runat="server">
- </asp:DropDownList>
- </div>
- </form>
- </body>
- </html>
Server-side code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Script.Services;
- using System.Web.Services;
- using System.Web.UI;
- using System.Web.UI.WebControls;
-
- namespace XMLWrite
- {
- public partial class BindDropDown : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- { }
-
- public class StudentDetails
- {
- public int Id { get; set; }
- public string Name { get; set; }
- }
-
- [WebMethod]
- public static List<StudentDetails> GetStudentDetails()
- {
- List<StudentDetails> lstStudentDetails = new List<StudentDetails>();
- StudentDetails studentDetails = new StudentDetails();
- studentDetails.Id = 1;
- studentDetails.Name = "Pradosh";
- lstStudentDetails.Add(studentDetails);
- studentDetails = new StudentDetails();
- studentDetails.Id = 2;
- studentDetails.Name = "Bibhu";
- lstStudentDetails.Add(studentDetails);
- studentDetails = new StudentDetails();
- studentDetails.Id = 3;
- studentDetails.Name = "Niladri";
- lstStudentDetails.Add(studentDetails);
- studentDetails = new StudentDetails();
- studentDetails.Id = 4;
- studentDetails.Name = "Brahma";
- lstStudentDetails.Add(studentDetails);
- return lstStudentDetails;
- }
- }
- }
Summary
I hope the above example will help you to bind the dropdown using JavaScript.