首页 > 代码库 > 在ASP.NET MVC中使用typeahead.js支持预先输入,即智能提示
在ASP.NET MVC中使用typeahead.js支持预先输入,即智能提示
使用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="http://www.mamicode.com/~/Content/TypeHead.css" rel="stylesheet" />}<div style="margin: 50px;">
<input class="typeahead" type="text" placeholder="输入城市名称"></div>@section scripts{<script src="http://www.mamicode.com/~/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>}
如何同时支持拼音和汉字的预先输入、智能提示呢?My dear friends, Any idea?
在ASP.NET MVC中使用typeahead.js支持预先输入,即智能提示
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。