【问题标题】:How to add Search Functionality to a dropdownlist in asp.net using Select2.js如何使用 Select2.js 将搜索功能添加到 asp.net 中的下拉列表
【发布时间】:2018-12-20 04:47:11
【问题描述】:

我有一个带有 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。 请帮帮我。

【问题讨论】:

    标签: c# jquery asp.net bootstrap-4 master-pages


    【解决方案1】:

    你可以简单地使用:

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

    【讨论】:

      【解决方案2】:

      尝试将 DropDownList 的 ClientIDMode 属性设置为静态。

      【讨论】:

      • 谢谢,它有效,我的第二个问题是它是在内容页面上执行所需脚本的最佳方法还是我应该移动它 MasterPage
      • 视情况而定,如果脚本需要在每个页面上运行,请将其保存在 master 中。如果它特定于某个内容页面,请将其移至该特定页面。
      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2017-07-04
      • 2017-02-03
      • 2015-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多