1 效果
当在一个文本框中输入时,可以自动查找相关选项,然后加载出来以供参考
2 前台代码
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<input type="text" id="city" name="city" />
<script type="text/javascript">
$("input#city").autocomplete({
source: "/mix/CityAutoComplete",
minLength: 1,
select: function (event, ui) {
alert("Select " + ui.item.label);
}
});
</script>
3 后台代码
此处的参数一定要是term的字符串,该字符串为当前在文本框中输入的值。在这里,自动找出与当前输入城市相同省份的城市。
public ActionResult CityAutoComplete(string term)
{
var cities = new List<City> {
new City{Id=1,Name="厦门",Province="福建省"},
new City{Id=1,Name="福州",Province="福建省"},
new City{Id=1,Name="泉州",Province="福建省"},
new City{Id=1,Name="西安",Province="陕西省"},
new City{Id=1,Name="长沙",Province="湖南省"},
new City{Id=1,Name="贵州",Province="湖北省"},
new City{Id=1,Name="包头",Province="甘肃省"},
new City{Id=1,Name="杭州",Province="浙江省"}
};
var currentCity = cities.FirstOrDefault(x => x.Name == term);
var projection = from city in cities
where city.Province == currentCity.Province
select new{
id = city.Id,
label = city.DisplayName,
value = city.DisplayName
};
return Json(projection.ToList(), JsonRequestBehavior.AllowGet);
}