ASP.NET MVC 5与jQuery UI的自动完成(AutoComplete)功能结合,可以创建强大的搜索框体验。这种组合允许用户在输入时实时获取建议,提升用户体验并减少输入错误。
首先,确保项目中引用了jQuery和jQuery UI库:
<!-- 在_Layout.cshtml或具体视图文件中添加 -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="ui-widget">
<label for="searchBox">搜索: </label>
<input id="searchBox" class="form-control" />
</div>
在ASP.NET MVC控制器中创建一个返回JSON数据的方法:
public ActionResult Search(string term)
{
// 这里替换为实际的数据源查询
var suggestions = new List<string>
{
"Apple",
"Banana",
"Cherry",
"Date",
"Fig",
"Grape",
"Kiwi",
"Lemon",
"Mango"
};
// 过滤匹配项
var filteredItems = suggestions
.Where(s => s.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0)
.ToList();
return Json(filteredItems, JsonRequestBehavior.AllowGet);
}
$(function() {
$("#searchBox").autocomplete({
source: function(request, response) {
$.ajax({
url: "/Home/Search", // 替换为你的控制器路径
dataType: "json",
data: {
term: request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 2, // 开始搜索前需要输入的最小字符数
delay: 300, // 延迟时间(毫秒)
select: function(event, ui) {
// 选中项时的处理
console.log("Selected: " + ui.item.value);
}
});
});
原因:
解决:
原因:
解决:
原因:
解决:
$("#searchBox").autocomplete({
source: "/Home/Search",
minLength: 2,
select: function(event, ui) {
// 处理选择
}
}).autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<div>" + item.label + "<br>" + item.desc + "</div>")
.appendTo(ul);
};
public ActionResult Search(string term)
{
var items = new List<SearchItem>
{
new SearchItem { Id = 1, Name = "Apple", Category = "Fruit" },
new SearchItem { Id = 2, Name = "Carrot", Category = "Vegetable" }
};
var filtered = items
.Where(i => i.Name.Contains(term) || i.Category.Contains(term))
.Select(i => new { label = i.Name, value = i.Id, category = i.Category })
.ToList();
return Json(filtered, JsonRequestBehavior.AllowGet);
}
public ActionResult Search(string term)
{
using (var db = new YourDbContext())
{
var results = db.Products
.Where(p => p.Name.Contains(term))
.Take(10)
.Select(p => new { label = p.Name, value = p.Id })
.ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
}
通过以上实现,你可以在ASP.NET MVC 5应用中创建一个功能强大且用户友好的自动完成搜索框。
没有搜到相关的文章