Using typeahead. js in ASP. net mvc supports preinput, that is, smart prompts, mvctypeahead. js
You can use typeahead. js to implement advance input, that is, smart prompts. This article is implemented in ASP. net mvc. The implementation result is as follows:
The first is the city model.
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public string PinYin { get; set; }
}
Return the json data about the City in response to the frontend request in HomeController.
public ActionResult GetCitiesJson()
{
var result = new List<City>()
{
New City () {Id = 1, Name = "qingdao", PinYin = "qingdao "},
New City () {Id = 10, Name = "qingshan", PinYin = "qingshan "},
New City () {Id = 11, Name = "qingfeng", PinYin = "qingfeng "},
New City () {Id = 2, Name = "wuhan", PinYin = "wuhan "},
New City () {Id = 3, Name = "yantai", PinYin = "yantai "},
New City () {Id = 4, Name = "Harbin", PinYin = "haerbing "},
New City () {Id = 5, Name = "beijing", PinYin = "beijing "},
New City () {Id = 6, Name = "Anyang", PinYin = "angyang "},
New City () {Id = 7, Name = "changchun", PinYin = "changchun "},
New City () {Id = 8, Name = "dongyang", PinYin = "dongyang "},
New City () {Id = 9, Name = "Gezhouba", PinYin = "gezhoubei "}
};
return Json(result,JsonRequestBehavior.AllowGet);
}
First load the City set in the view, and then use the pre-input function.
@section styles
{
<link href="~/Content/TypeHead.css" rel="stylesheet" />
}
<div>margin: 50px;">
<Input class = "typeahead" type = "text" placeholder = "input city name">
</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);
});
}
});
// Pre-Input Function
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'city',
displayKey: 'value',
source: substringMatcher(cities)
});
});
var cities = [];
// The arr parameter indicates the data source array.
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>
}
How can we support preinput and smart prompts for both Pinyin and Chinese characters? My dear friends, Any idea?