官网
http://api.jqueryui.com/autocomplete/
1. Source属性可以为Json对象,label为下拉列表选中后出现在textbox的值,value是下拉列表让user选择的值
[ { label: "Choice1", value: "value1" }, ... ]
通常我们会另加个id值来标志每个选项
后台
public String GetLangSource() { IEnumerable<Langeuage> langList = GetAllLangs.ToList(); // [ { label: "Choice1", value: "value1" }, ... ] string list = "["; foreach (Language lang in langList) { list += "{"label":"" + lang.Name + "","value":"" + lang.Name + "","id":"" + lang.Id.ToString() + ""},"; } list += "]"; return list; }
前台
$("#SelectLang").autocomplete({ source: eval($('#LangSource').val()), mustMatch: true });
2.Source属性也可以为一个http地址,使用get方法来每次实时获取数据源
后台
public JsonResult GetLangSource() { IEnumerable<Langeuage> langList = GetAllLangs.ToList(); List<object> list = new List<object>(); foreach (Language lang in langList) { var obj = new { label = lang.Name, value = lang.Name, id = lang.Id.ToString() }; list.Add(obj); } return Json(list, JsonRequestBehavior.AllowGet); }
前台
$("#SelectLang").autocomplete({ source: '@Url.Action("GetLangSource")', mustMatch: true });
3.清空user随便输入非数据源的字符串
$("#SelectLang").autocomplete({ source: '@Url.Action("GetLangSource")', mustMatch: true, change: function (event, ui) { if ($.trim($(event.target).val()) == "") { $("#SelectLangId").val(0); return; } }, select: function (event, ui) { $("#SelectLangId").val(ui.item.id); }, response: function (event, ui) { if (ui.content.length == 0) { $("#SelectLangId").val(0); $(event.target).val(""); return; } } });