简体   繁体   English

如何在 .net 核心 mvc 的搜索框中实现自动完成功能?

[英]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 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仪表板.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>

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.如果您在浏览器中查看上述 TextBox 的 html 源代码,您会发现它呈现如下。

在此处输入图像描述

The value of id attribute is " SearchString ", not " txtMovie ". id属性的值是“ SearchString ”,而不是“ txtMovie ”。 You can try to modify the code to use $("#SearchString") selector, like below.您可以尝试修改代码以使用$("#SearchString")选择器,如下所示。

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

Test result with testing data测试结果与测试数据

在此处输入图像描述

Note: please make sure you add references to required jquery libraries.注意:请确保添加对所需 jquery 库的引用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM