如何将自动完成(使用AJAX)添加到我现有的搜索文本框
如何使用绑定到数据源(包含表课程的表)的AJAX进行自动完成的文本框?当前,文本框返回搜索的“课程”名称。
我在_layout.cshtml文件中有这个。
<form class="form-inline my-2 my-lg-0" asp-controller="Courses" asp-action="Filter" style="padding-right: 25px;">
<input name="searchString" type="text" class="form-control" placeholder="Search for a course...">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"><i class="bi bi-search"></i></button>
</form>
我在我的coursescontroller.cs文件中有这个。
[AllowAnonymous]
public async Task<IActionResult> Filter(string searchString)
{
var allCourses = await _service.GetAllAsync(n => n.Difficulty);
if (!string.IsNullOrEmpty(searchString))
{
var filteredResult = allCourses.Where(n => n.Name.ToLower().Contains(searchString.ToLower()) || n.Description.ToLower().Contains(searchString.ToLower())).ToList();
return View("Index", filteredResult);
}
return View("Index", allCourses);
}
在此先感谢您的任何帮助!
How would I make an autocomplete textbox using AJAX that binds to data source (table containing Courses)? Currently, the textbox returns a 'Course' name that is searched.
I have this in my _Layout.cshtml file.
<form class="form-inline my-2 my-lg-0" asp-controller="Courses" asp-action="Filter" style="padding-right: 25px;">
<input name="searchString" type="text" class="form-control" placeholder="Search for a course...">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"><i class="bi bi-search"></i></button>
</form>
And I have this in my CoursesController.cs file.
[AllowAnonymous]
public async Task<IActionResult> Filter(string searchString)
{
var allCourses = await _service.GetAllAsync(n => n.Difficulty);
if (!string.IsNullOrEmpty(searchString))
{
var filteredResult = allCourses.Where(n => n.Name.ToLower().Contains(searchString.ToLower()) || n.Description.ToLower().Contains(searchString.ToLower())).ToList();
return View("Index", filteredResult);
}
return View("Index", allCourses);
}
Thanks in advance for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用AJAX意味着您将调用API以在后台获取数据,这意味着当您的页面满载时,您将执行呼叫的后端来获取课程列表。
假设您在用户单击按钮(或您感兴趣的任何事件)时使用jQuery,
我们将调用一种致电给您的后端的方法:
在您的CoursesController上,您将拥有一种将课程返回为课程的方法JSON结果。 (假设您有用于访问数据的实体框架)
using AJAX means you will call an API to get data in the background, this means when your page is fully loaded, you will perform a call to your backend to get the list of courses.
assuming you are using JQuery when the user clicks on a button (or any event that you are interested in)
we will call a method that makes a call to your backend:
and on your CoursesController, you will have a method that returns the courses as a JSON result. (assuming you have EntityFramework for data accessing)