2014-02-19 45 views
1

我需要有一個DropDownList或同等ASP.NET MVC在一個視圖,其中填充了一堆來自數據庫的條目。DropDownList與文本框輸入作爲過濾標準

選中時,DropDownList應該照常生成列表,但用戶可以在其中輸入文本,此時DropDownList中的項目將根據輸入的文本進行過濾。

用戶應該仍然只能選擇列表中的一個選項。

它可以是任何其他控件,但最好不是第三方的東西。

回答

1

我發現,工作體面的方法。

唯一的問題是它需要2個獨立的控件(DropDownListTextBox),但除此之外,它的工作原理非常漂亮。

HTML代碼(控件聲明)是:

<table> 
    <tr> 
     <td> 
      <div> 
       <%: Html.Label("Search Filter:")%> 
      </div> 
     </td> 
     <td> 
      <div> 
       <%: Html.TextBox("textBoxForFilterInput")%> 
      </div> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <div> 
       <%: Html.Label("The List")%> 
      </div> 
     </td> 
     <td> 
      <div> 
       <%: Html.DropDownList("listOfOptions")%> 
      </div> 
     </td> 
    </tr> 
</table> 

的JavaScript代碼是:

$(function() { 
     var opts = $('#listOfOptions option').map(function() { 
      return [[this.value, $(this).text()]]; 
     }); 

     $('#textBoxForFilterInput').keyup(function() { 
      var rxp = new RegExp($('#textBoxForFilterInput').val(), 'i'); 
      var optlist = $('#listOfOptions').empty(); 
      opts.each(function() { 
       if (rxp.test(this[1])) { 
        optlist.append($('<option/>').attr('value', this[0]).text(this[1])); 
       } 
      }); 
     }); 
    }); 

然後,只需填充#listOfOptions,然後你要善於去。

或者,您可以將它掛接到預定義的列表/數組或像我一樣從數據庫中獲取它。

這工作就像一個魅力,非常簡單,超級快。

感謝DMI發送給我正確的道路。

他的工作可以在here找到。

1

可以通過編寫一些jQuery代碼。但是,已經可用,它是開源的,廣泛使用的

使用jQuery chosen和配置像下面

$(".select").chosen(); 
+0

我不能得到這個工作。我包括在該文件甚至.chosen方法與智能感知彈出,但我不斷收到一個錯誤: 對象不支持此屬性或方法「選擇」 – HowlinWulf

0

對於這個.autoComplete的jQuery都可以使用。

HTML就像

<table><tr><td><input type="textbox" id="textBoxid" /> <div id="targetDiv" style="z-index:10"></div>

jQuery代碼會像

$(function() { 
     $("#textBoxid").autocomplete({ 
      appendTo: "#targetDiv", 
      position: { at: "bottom bottom" }, 
      source: function (request, response) { 
       $.ajax({ 
        url: '@Url.Action("ActionMethod", "Controller")', 
        type: "POST", 
        dataType: "json", 
        data: { searchString: request.term }, 
        success: function (data) { 
         response($.map(data, function (item) { 
          return { label: item.ColumnValue, Id:item.ColumnId } 
         })) 
        } 
       }) 
      }, 
      select: function (event, ui) { 
       if (ui.item) { 
// for saving the selected item id or any other function you wanna perform on selection 
        $('#hiddenfield').val($.trim(ui.item.Id)); 
       } 
      } 
     }); 

操作方法會像

 [HttpPost] 
     public JsonResult MaterialDesc(string searchString) 
     { 

//在搜索字符串的基礎,你可以有你的代碼從數據庫中獲取數據。 }

希望它可以幫助你 :)