文章詳情頁
ASP.NET MVC使用typeahead.js實現輸入智能提示功能
瀏覽:118日期:2022-06-08 11:48:34
使用typeahead.js可以實現預先輸入,即智能提示,本篇在ASP.NET MVC下實現。實現效果如下:
首先是有關城市的模型。
public class City {public int Id { get; set; }public string Name { get; set; }public string PinYin { get; set; } }
在HomeController中響應前端請求返回有關City的json數據。
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 = [];//參數arr表示數據源 數組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>}
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對的支持。如果你想了解更多相關內容請查看下面相關鏈接
標簽:
ASP.NET
相關文章:
1. ASP.NET MVC使用異步Action的方法2. ASP.Net MVC利用NPOI導入導出Excel的示例代碼3. 使用EF Code First搭建簡易ASP.NET MVC網站并允許數據庫遷移4. ASP.NET MVC實現城市或車型三級聯動5. ASP.NET MVC使用Session會話保持表單狀態6. ASP.NET MVC通過勾選checkbox更改select的內容7. ASP.NET MVC擴展帶驗證的單選按鈕8. ASP.NET MVC遍歷驗證ModelState的錯誤信息9. ASP.NET MVC使用Quartz.NET執行定時任務10. ASP.NET MVC增加一條記錄同時添加N條集合屬性所對應的個體
排行榜
