Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

c# - how to implement autocomplete functionality in search box in .net core mvc?

I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works. I followed different tutorials but not able to solve it. Please take a look and give me the direction. Thnx in advance.

Controller

 public async Task<IActionResult> dashboard(string sortOrder, string SearchString)
        {
            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
           
            var movies = from m in _context.Movie
                         select m;
            if (!String.IsNullOrEmpty(SearchString))
            {
                movies = movies.Where(s => s.MovieName.Contains(SearchString));
            }
            switch (sortOrder)
            {
                case "name_desc":
                    movies = movies.OrderByDescending(s => s.MovieName);
                    break;
                
                default:
                    movies = movies.OrderBy(s => s.MovieName);
                    break;
            }
            return View(await movies.AsNoTracking().ToListAsync());
        }
        
 
         public JsonResult AutoComplete(string prefix)  
         {
             var customers = (from movie in this._context.Movie
                              where movie.MovieName.StartsWith(prefix)
                              select new
                              {
                                  label = movie.MovieName,
                                  val = movie.Id
                              }).ToList();

             return Json(customers);
         }

dashboard.cshtml

@model IEnumerable<WebApplication1.Models.Movie>

@{
    ViewData["Title"] = "dashboard";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>Dashboard</h1>
@using (Html.BeginForm())
{
<p>
    Find by Movie Name:  @Html.TextBox("SearchString")
    <input type="hidden" id="hfCustomer" name="Id" />
    <input type="submit" value="Search" />
</p>
}

<table class="table">
    <thead>
        <tr>
            <th>
                <a asp-action="dashboard" asp-route-sortOrder="@ViewData["NameSortParm"]">@Html.DisplayNameFor(model => model.MovieName)</a>
            </th>

            

            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.MovieName)
                </td>
               </tr>
        }
    </tbody>
</table>

<script type="text/javascript">
        $(function () {
            $("#txtMovie").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/Movies/AutoComplete/',
                        data: { "prefix": request.term },
                        type: "POST",
                        success: function (data) {
                            response($.map(data, function (item) {
                                return item;
                            }))
                        },
                        error: function (response) {
                            alert(response.responseText);
                        },
                        failure: function (response) {
                            alert(response.responseText);
                        }
                    });
                },
                select: function (e, i) {
                    $("#hfCustomer").val(i.item.val);
                },
                minLength: 1
            });
        });
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I tried to add autocomplete or suggestion functionality in search box of view, as when some one enter any character, any word containing that character shows as suggestion, but this not works.

Find by Movie Name:  @Html.TextBox("SearchString")

If you check the html source code of above TextBox in your browser, you would find it is rendered as below.

enter image description here

The value of id attribute is "SearchString", not "txtMovie". You can try to modify the code to use $("#SearchString") selector, like below.

$("#SearchString").autocomplete({
    //...
    //code logic here
    //...  

Test result with testing data

enter image description here

Note: please make sure you add references to required jquery libraries.

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...