【问题标题】:Editable Dropdown in C#C# 中的可编辑下拉菜单
【发布时间】:2015-03-16 11:46:13
【问题描述】:

我需要创建一个下拉列表,用户可以在其中从下拉列表中选择一个值或输入该值。

就像下面链接中的“你来自哪里?”下拉菜单:

http://www.dhtmlgoodies.com/scripts/form_widget_editable_select/form_widget_editable_select.html

我知道这是一个常见问题,也有关于堆栈溢出的类似查询,但我找不到一个简单的工作解决方案。

我参考了以下链接:

http://www.codeproject.com/Articles/8578/Editable-Dropdown-DHTML-Behavior http://www.codeproject.com/Articles/290218/Custom-ASP-NET-Editable-DropDownList http://codeverge.com/asp.net.web-forms/editable-dropdown-list-c/392261

以前有没有人做过这方面的工作并告诉我如何进行?

【问题讨论】:

  • 你想要一个 ComboBox,通常是一个 WebForms 控件,但在 AjaxControlToolkit 中有一个:asp.net/web-forms/overview/ajax-control-toolkit/combobox/…
  • @Hugo- 我会调查并告诉你!
  • 我推荐 Select2,可以在这里找到:select2.github.io
  • @Hugo - 我尝试关注这篇文章,但我猜组合框不能在 Web 窗体中使用。显然,如果我没记错的话,它仅适用于 Windows 窗体应用程序。如果我错了,请纠正我!
  • 它们确实不是 WebForms 中最简单的东西,但该链接用于在 WebForm 上使用它。您需要AjaxControlToolkit,您可以将其作为 NuGet 包获取。

标签: c# asp.net drop-down-menu webforms


【解决方案1】:

另一种解决方法如下
您可以使用 Ajax Control Toolkit Nuget

第 1 步: 在您的参考文献中添加来自 Nuget 包的 Ajax 控件工具包

第 2 步: 如果您没有将 Ajax Control Toolkit 控件放入工具箱,则需要创建一个单独的选项卡并将其命名为 Ajax Toolkit Controls。
然后右键单击它并选择选择项目。
浏览到 Ajax Control Toolkit 的 dll 所在的位置,选择它。
您将看到一组控件填充到窗口中。
选择 Ok,这将导致使用 Ajax Control Toolkit Controls 填充选项卡。

第 3 步: 由于 Ajax Toolkit Controls 是一个额外的附加包,因此您需要将它们注册为使用它们的页面的一部分。如果安装为 nuget,则可以忽略此步骤。

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>

注意:标记前缀应与您在程序中为 AjaxControlToolkit 控件使用的标记前缀匹配。

第 4 步: 添加 ScriptManager 控件,它是为客户端 AJAX 功能提供支持所必需的。因此,它会加载并注册 Microsoft AJAX 库以启用这些功能。

<asp:ScriptManager ID="ScriptManager1" runat="server" />

第 5 步: 继续从工具箱中添加 ComboBox 并通过使用 SQLDataSource 将其链接到数据库来配置它

完整源码如下

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

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <style type="text/css">
        #ComboBox1_ComboBox1_OptionList {
            width: 10% !important;
        }
    </style>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
            <ajaxToolkit:ComboBox ID="ComboBox1" AppendDataBoundItems="True" runat="server" AutoCompleteMode="Suggest" DataSourceID="SqlDataSource1" DataTextField="Fruits" DataValueField="Fruits" MaxLength="0" Style="display: inline;">
            </ajaxToolkit:ComboBox>
            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:FruitsConnectionString %>" SelectCommand="SELECT * FROM [Fruits]"></asp:SqlDataSource>
        </div>
    </form>
</body>
</html>

我已在以下所有设置测试环境中测试了此代码:
Chrome 浏览器版本 43.0.2334.0 dev-m(64 位)
Internet Explorer 11
火狐 36.0.1
Visual Studio 2013 版

【讨论】:

  • 它给了我一个错误:错误 5 命名空间“AjaxControlToolkit”中不存在类型或命名空间名称“ComboBox”(您是否缺少程序集引用?)
  • 您是否在参考资料中包含了 AjaxControlToolkit?如果不尝试再次安装整个 AjaxControlToolkit 以及 Nuget 市场中的其他工具和包。
【解决方案2】:

您可以尝试使用 JqueryUI 自动完成组合框。
它可以让您输入文本以及从下拉列表中选择您选择的项目。
作为一项额外功能,您可以使用自动完成功能来增强 UI 体验。

我附上了一个与 bootstrap 3.3.4 结合的演示

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">
  <title></title>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
  <link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />

  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <link href="https://jqueryui.com/resources/demos/style.css" rel="stylesheet" />
  <style>
    .custom-combobox {
      position: relative;
      display: inline-block;
    }
    .custom-combobox-toggle {
      position: absolute;
      top: 0;
      bottom: 0;
      margin-left: -1px;
      padding: 0;
    }
    .custom-combobox-input {
      margin: 0;
      padding: 5px 10px;
    }
    .ui-state-default,
    .ui-widget-content .ui-state-default,
    .ui-widget-header .ui-state-default {
      border: 1px solid #421D1D;
      background: #ffffff url("images/ui-bg_glass_75_e6e6e6_1x400.png") 50% 50% repeat-x !important;
      font-weight: normal;
      color: #555555;
    }
    /* Corner radius */
    .ui-corner-all,
    .ui-corner-top,
    .ui-corner-left,
    .ui-corner-tl {
      border-top-left-radius: 0px !important;
    }
    .ui-corner-all,
    .ui-corner-top,
    .ui-corner-right,
    .ui-corner-tr {
      border-top-right-radius: 0px !important;
    }
    .ui-corner-all,
    .ui-corner-bottom,
    .ui-corner-left,
    .ui-corner-bl {
      border-bottom-left-radius: 0px !important;
    }
    .ui-corner-all,
    .ui-corner-bottom,
    .ui-corner-right,
    .ui-corner-br {
      border-bottom-right-radius: 0px !important;
    }
  </style>
  <script>
    (function($) {
      $.widget("custom.combobox", {
        _create: function() {
          this.wrapper = $("<span>")
            .addClass("custom-combobox")
            .insertAfter(this.element);

          this.element.hide();
          this._createAutocomplete();
          this._createShowAllButton();
        },

        _createAutocomplete: function() {
          var selected = this.element.children(":selected"),
            value = selected.val() ? selected.text() : "";

          this.input = $("<input>")
            .appendTo(this.wrapper)
            .val(value)
            .attr("title", "")
            .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
            .autocomplete({
              delay: 0,
              minLength: 0,
              source: $.proxy(this, "_source")
            })
            .tooltip({
              tooltipClass: "ui-state-highlight"
            });

          this._on(this.input, {
            autocompleteselect: function(event, ui) {
              ui.item.option.selected = true;
              this._trigger("select", event, {
                item: ui.item.option
              });
            },

            autocompletechange: "_removeIfInvalid"
          });
        },

        _createShowAllButton: function() {
          var input = this.input,
            wasOpen = false;

          $("<a>")
            .attr("tabIndex", -1)
            .attr("title", "Show All Items")
            .tooltip()
            .appendTo(this.wrapper)
            .button({
              icons: {
                primary: "ui-icon-triangle-1-s"

              },
              text: false
            })
            .removeClass("ui-corner-all")
            .addClass("custom-combobox-toggle ui-corner-right")
            .mousedown(function() {
              wasOpen = input.autocomplete("widget").is(":visible");
            })
            .click(function() {
              input.focus();

              // Close if already visible
              if (wasOpen) {
                return;
              }

              // Pass empty string as value to search for, displaying all results
              input.autocomplete("search", "");
            });
        },

        _source: function(request, response) {
          var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
          response(this.element.children("option").map(function() {
            var text = $(this).text();
            if (this.value && (!request.term || matcher.test(text)))
              return {
                label: text,
                value: text,
                option: this
              };
          }));
        },

        _removeIfInvalid: function(event, ui) {

          // Selected an item, nothing to do
          if (ui.item) {
            return;
          }

          // Search for a match (case-insensitive)
          var value = this.input.val(),
            valueLowerCase = value.toLowerCase(),
            valid = false;
          this.element.children("option").each(function() {
            if ($(this).text().toLowerCase() === valueLowerCase) {
              this.selected = valid = true;
              return false;
            }
          });

          // Found a match, nothing to do
          if (valid) {
            return;
          }

          // Remove invalid value
          this.input
            .val("")
            .attr("title", value + " didn't match any item")
            .tooltip("open");
          this.element.val("");
          this._delay(function() {
            this.input.tooltip("close").attr("title", "");
          }, 2500);
          this.input.autocomplete("instance").term = "";
        },

        _destroy: function() {
          this.wrapper.remove();
          this.element.show();
        }
      });
    })(jQuery);

    $(function() {
      $("#combobox").combobox();
      $("#toggle").click(function() {
        $("#combobox").toggle();
      });
    });
  </script>
</head>

<body>
  <form id="form1" runat="server">
    <div>
      <div class="ui-widget">
        <select id="combobox" class="form-control">
          <option value="">Select your option</option>
          <option value="Apple">Apple</option>
          <option value="Banana">Banana</option>
          <option value="Cherry">Cherry</option>
          <option value="Date">Date</option>
          <option value="Fig">Fig</option>
          <option value="Grape">Grape</option>
          <option value="Kiwi">Kiwi</option>
          <option value="Mango">Mango</option>
          <option value="Orange">Orange</option>
          <option value="Pumpkin">Pumpkin</option>
          <option value="Strawberry">Strawberry</option>
          <option value="Tomato">Tomato</option>
          <option value="Watermelon">Watermelon</option>
        </select>
      </div>

    </div>
  </form>
</body>

</html>
我已经在以下所有设置上测试了这段代码 测试环境:
Chrome 浏览器版本 43.0.2334.0 dev-m(64 位)
Internet Explorer 11
火狐 36.0.1
Visual Studio 2013 版

希望这能解决您的问题。

【讨论】:

  • 值是否可能来自数据库?
  • 是的,要从数据库中获取它们,您必须使用 WCF/.asmx WebService 从 C# 中的数据库中查询它们,并通过 C# 中的 WebMethod 将它们作为 JSON 附加到下拉列表中
  • 天哪!我不知道 WCF 和 JSON。没有其他办法了吗?
【解决方案3】:

这个 JQuery 插件将解决您的问题,它将 DropDown 列表变成类似字段的自动完成,即使它改变了选择元素的 HTML 结构 ASP.NET 仍然能够检测到哪个选项被选中。

来源:https://github.com/indrimuska/jquery-editable-select

OBS:要将数据持久化到回发,您需要将与回发关联的事件与 JavaScript 绑定,再次将“组合框”设为下拉列表(使用持久化值)。

示例用法:

$('#editable-select').editableSelect();
<link href="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet">
<select id="editable-select">
    <option>Alfa Romeo</option>
    <option>Audi</option>
    <option>BMW</option>
    <option>Citroen</option>
</select>
<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//rawgithub.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2018-05-16
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多