文章詳情頁
ASP.NET MVC使用typeahead.js實現(xiàn)輸入智能提示功能
瀏覽:525日期:2022-06-08 11:48:34
使用typeahead.js可以實現(xiàn)預先輸入,即智能提示,本篇在ASP.NET MVC下實現(xiàn)。實現(xiàn)效果如下:

首先是有關(guān)城市的模型。
public class City {public int Id { get; set; }public string Name { get; set; }public string PinYin { get; set; } }在HomeController中響應前端請求返回有關(guān)City的json數(shù)據(jù)。
public ActionResult GetCitiesJson(){ var result = new List<City>() {new City(){Id = 1, Name = "青島",PinYin = "qingdao"},new City(){Id = 10, Name = "青山",PinYin = "qingshan"},new City(){Id = 11, Name = "青峰",PinYin = "qingfeng"},new City(){Id = 2, Name = "武漢",PinYin = "wuhan"},new City(){Id = 3, Name = "煙臺",PinYin = "yantai"},new City(){Id = 4, Name = "哈爾濱",PinYin = "haerbing"},new City(){Id = 5, Name = "北京",PinYin = "beijing"},new City(){Id = 6, Name = "安陽",PinYin = "angyang"},new City(){Id = 7, Name = "長春",PinYin = "changchun"},new City(){Id = 8, Name = "東陽",PinYin = "dongyang"},new City(){Id = 9, Name = "葛洲壩",PinYin = "gezhoubei"} }; return Json(result,JsonRequestBehavior.AllowGet);}在視圖中先加載City集合,再使用預先輸入功能。
@section styles{ <link href="~/Content/TypeHead.css" rel="external nofollow" rel="stylesheet" />}<div> <input type="text" placeholder="輸入城市名稱"></div>@section scripts{ <script src="~/Scripts/typeahead.bundle.js"></script> <script type="text/javascript">$(function () { $.getJSON("@Url.Action("GetCitiesJson","Home")", function(data) {if (data) { $.each(data, function(index, city) {cities.push(city.Name); });} }); //預先輸入功能 $(".typeahead").typeahead({hint: true,highlight: true,minLength: 1 }, {name: "city",displayKey: "value",source: substringMatcher(cities) });});var cities = [];//參數(shù)arr表示數(shù)據(jù)源 數(shù)組var substringMatcher = function (arr) { return function findMatches(q, cb) {var substrRegex;var matches = [];substrRegex = new RegExp(q, "i");$.each(arr, function (i, ele) { if (substrRegex.test(ele)) {matches.push({ value: ele }); } });cb(matches); };}; </script>}以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
標簽:
ASP.NET
相關(guān)文章:
1. ASP.NET MVC獲取多級類別組合下的產(chǎn)品2. ASP.NET MVC前臺動態(tài)添加文本框并在后臺使用FormCollection接收值3. ASP.NET MVC實現(xiàn)單個圖片上傳、限制圖片格式與大小并在服務端裁剪圖片4. ASP.NET MVC使用Log4Net記錄異常日志并跳轉(zhuǎn)到靜態(tài)頁5. ASP.NET MVC解決上傳圖片臟數(shù)據(jù)的方法6. ASP.NET MVC使用jQuery的Load方法加載靜態(tài)頁面及注意事項7. ASP.NET MVC遍歷驗證ModelState的錯誤信息8. ASP.NET MVC實現(xiàn)登錄后跳轉(zhuǎn)到原界面9. log4net在Asp.net MVC4中的使用過程10. ASP.NET MVC實現(xiàn)橫向展示購物車
排行榜

網(wǎng)公網(wǎng)安備