如何使用 Select2.js 将搜索功能添加到 asp.net 中的下拉列表

我有一个带有 MasterPage 的项目。我在这里添加了一个内容页面名称 AddEmployeeDetail.aspx


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

在内容页面 AddEmployeeDetail.aspx 中,我有一个名为 ddEmployeeName 的下拉列表。在页面加载时,此下拉列表从数据库中填充 EmployeeName。这是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>

这是.cs文件代码


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;

}

我还在这个 AddEmployeeDetail.aspx 内容页面中添加了一个脚本文件,它是:


 <script>

    $(document).ready(function () {

     $("#ddEmployeeName").select2({

        placeholder: "Select an option",

        allowClear: true

     });

 });

</script>

还有一个 Jquery.js 和 Select2.js 文件的链接,它是


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

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

这两个文件都在内容占位符中。现在我想,在页面加载和数据进入下拉列表后,当用户点击下拉列表时,他/她应该能够搜索任何特定数据然后选择它。简而言之,我想将搜索功能添加到下拉列表中。到目前为止,我做了什么,它不起作用。它加载数据但不添加搜索功能。我不知道是什么问题。另外,如果在 MasterPage 而不是内容页面中添加脚本和脚本文件,它会起作用吗?我正在使用BS4。请帮帮我。


qq_花开花谢_0
浏览 143回答 2
2回答

狐的传说

您可以简单地使用:$("#<%=ddEmployeeName.ClientID%>").select2({&nbsp; &nbsp; placeholder: "Select an option",&nbsp; &nbsp; allowClear: true});

饮歌长啸

尝试将 DropDownList 的 ClientIDMode 属性设置为静态。
打开App,查看更多内容
随时随地看视频慕课网APP