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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…