Avil Levis
Avil Levis

Reputation: 1

How to add autocomplete (using AJAX) to my existing search textbox

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!

Upvotes: 0

Views: 548

Answers (1)

YoussefSell
YoussefSell

Reputation: 157

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)

<button id="searchBtn" type="button">Search</button>

we will call a method that makes a call to your backend:

$("#searchBtn").click(function(){
    // load the data when the button is clicked
    loadData();
}); 

function loadData() {
    $.ajax({
        url: '@Url.Action("GetCourses", "Courses")',
        type: "GET",
        data: {
            // get the value from your input with id = "search-query"
            searchQuery: $("#search-query").val()
        },
        success: function (result) {
            // here you have your data
            // so now you can render the result to your list or table
           console.log(result);
        },
        error: function (error) {
            // here something went wrong
           console.log(error);
        },
    });
}

and on your CoursesController, you will have a method that returns the courses as a JSON result. (assuming you have EntityFramework for data accessing)

[AllowAnonymous]
[HttpGet]
public async Task<JsonResult> GetCoursesAsync(string searchQuery)
{
    var query = _dbContext.Courses.AsQueryable();

    if (!string.IsNullOrEmpty(searchQuery))
    {
        query = query.Where(c => 
                c.Name.Contains(searchQuery) ||
                c.Description.Contains(searchQuery)
        );
    }

    // load the courses
    var courses = await query.ToArrayAsync();

    // return the data as json result
    return new JsonResult(courses);
}

Upvotes: 1

Related Questions