我正在使用ASP.NET MVC平臺。在我的控制器中,我創建了ViewBag,它可以選擇數據庫中的所有名稱。我在我的視圖中有一個@ Html.listbox,我使用select2()ajax函數,用於在列表框中輸入時提示。例如,如果我寫「馬」,我會列出瑪麗亞,馬里奧,馬丁,因爲我有他們在數據庫中。我的問題是,我只能在它們之間進行選擇,而不是添加不在數據庫中的新名稱。你能給我任何想法或例子我怎麼能做到這一點?我想使用Google提供的一些建議,您鍵入,獲取建議,選擇一些內容,然後您可以對其進行更改並將其添加到模型中。ASP.NET MVC「可編輯」列表框
這裏是我的視圖代碼:
<div class="form-group">
@Html.LabelFor(model => model.Names, htmlAttributes: new { @class = "control-label col-md-3" })
<div class="col-md-6">
@Html.ListBoxFor(model => Model.Names, null, new { @class = "form-control input-sm" })
@Html.ValidationMessageFor(model => model.Names, "", new { @class = "text-danger" })
</div>
</div>
<script type="text/javascript">
$(function() {
$("#Names").select2({
placeholder: "Filter names",
maximumSelectionSize: 1,
});
});
</script>
,我在控制器做這在我的GET:
// GET: Names/Create
public ActionResult Create()
{
ViewBag.Names= new SelectList(db.Names.Select(n => n.Names));
return PartialView("_Create");
}
編輯:
我現在使用jQuery的自動完成這樣的:
<script type="text/javascript">
$(function() {
$("#tags").autocomplete(
{
source: '@Url.Action("TagSearch", "Home")'
});
})
</script>
我改變了我的html.textbox像這樣:
<div class="form-group">
<div class="col-md-6">
<div class="ui-widget">
@Html.TextBoxFor(model => Model.Names, null, new { @class = "form-control input-sm", @id = "tags" })
</div>
@Html.ValidationMessageFor(model => Model.Names, "", new { @class = "text-danger" })
</div>
</div>
另外我有一個返回JSON和它完美的作品,現在的問題是,當我在建議中鍵入的功能在部分視圖背後(在部分視圖和索引視圖之間)以及我無法選擇其中任何一個的形式(像大標籤......)。對此有何幫助?
jQuery的[自動完成](http://jqueryui.com/autocomplete/#multiple)允許你這樣做 – 2015-02-10 08:09:23
這看起來喜歡的事,可真對我有用,我正試圖在我的代碼中實現它。謝謝,你可以把它作爲答案發布,這樣我就可以在完成時接受它。 – KOmrAD 2015-02-10 08:36:12