首页 > 解决方案 > How to add Search Functionality to a dropdownlist in asp.net using Select2.js

问题描述

I have a Project with a MasterPage. I added a content page name AddEmployeeDetail.aspx which is here

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="AddEmployeeDetail.aspx.cs" Inherits="DeceasedSystem.AddEmployeeDetail" %>

Inside the content page AddEmployeeDetail.aspx i have a dropdownlist called ddEmployeeName. On page load, this dropdownlist is populated from the database with EmployeeName. Here is the HTML

<div class="form-group row">
    <label for="name" class="col-4 col-form-label">Employee Name</label>
    <div class="col-8">
        <asp:DropDownList ID="ddEmployeeName" runat="server" class="form-control here"></asp:DropDownList>
    </div>
</div>

Here is the .cs file code

protected void Page_Load(object sender, EventArgs e)
{
    ddEmployeeName.DataSource = LoadComboBoxEmployeeName();
    ddEmployeeName.DataTextField = "Name";
    ddEmployeeName.DataValueField = "Id";
    ddEmployeeName.DataBind();
    ddEmployeeName.Items.Insert(0, new ListItem("--Select--", "0"));
}

string CS = ConfigurationManager.ConnectionStrings["DeceasedDBCS"].ConnectionString;

//Load ComboBox Company
private DataTable LoadComboBoxEmployeeName()
{
    DataTable dtFatherName = new DataTable();
    using (SqlConnection con = new SqlConnection(CS))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableEmployeeMaster", con))
        {
            cmd.CommandType = CommandType.Text;
            con.Open();
            SqlDataReader r = cmd.ExecuteReader();
            dtFatherName.Load(r);
        }
    }
    
    return dtFatherName;
}

I also add a script file in this AddEmployeeDetail.aspx content page which is:

 <script>
    $(document).ready(function () {
     $("#ddEmployeeName").select2({
        placeholder: "Select an option",
        allowClear: true
     });
 });
</script>

and also a link of Jquery.js and Select2.js files which is

<script src="js/jquery.js"></script>
<script src="js/select2.js"></script>

Both the files are in content Placeholder. Now I want, After the page load and data comes to the dropdownlist, when a user clicks on the dropdownlist, he/she should be able to search for any specific data and then select that. In short, I want to add search functionality to dropdownlist. So far what have I done, it is not working. It loads data but doesn't add the search functionality. I don't know what is the problem. And also, will it work if added the scripts and script files in MasterPage instead of the content Page? I am using BS4. Help me Please.

标签: c#jqueryasp.netbootstrap-4master-pages

解决方案


您可以简单地使用:

$("#<%=ddEmployeeName.ClientID%>").select2({
    placeholder: "Select an option",
    allowClear: true
});

推荐阅读