在 c# mvc 代码中进行实时搜索后,如何使用值更新无序列表?

How do I update an Unordered List with values after a Live search in c# mvc code?

我想在文本框中键入时进行实时搜索以过滤结果。有一个 html 无序列表,它是在加载页面时从模型中填充的,这些是我在搜索时要过滤的项目。问题是如何使用搜索值更新 ul?

cshtml页面:

<div>
  <input id="search" type="text" placeholder="Search Sections">
  <ul id="menuList" style="max-height: 800px; overflow:scroll;">
      @foreach (var item in Model)
        {
         <li>
           <div style="display:inline-block; min-width:15%">@item.Index</div>
           <div style="display:inline; min-width:80%">@item.Title</div>
         </li>
        }
   </ul>
</div>

ajax 调用:

$(function () {
            $("#search").keyup(function (e) {
                var s = $("#search").val();
                $.get("/Document/GetSearchItem?searchString=" + s, function (r) {
                    //how do I update ui with results here?
                    

                });
            });
        });

查询数据库的控制器方法和returns我用来更新模型的列表,效果很好。

public async Task<IActionResult> GetSearchItem(string searchString)
        {
            var lst = await _sectionService.GetSearchString(searchString);
            var documentModel = new List<DocumentViewModel>();
            foreach (var item in lst)
            {
                documentModel.Add(new DocumentViewModel
                {
                    Id = item.Id.ToString(),
                    Title = item.Title,
                    Index = item.IndexNumber                    
                });
            }
            return View(documentModel);
        }

您只需使用 jQuery 手动完成。

查看此答案以获得一些想法:How to add items to a unordered list <ul> using jquery

我在我的一个 asp.net 项目中有类似的功能,并以这种方式处理 ajax 调用。检查是否有帮助。

function SearchText() {
        $("#search").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "samplepage.aspx/samplemethod",
                    data: "{'searchValue':'" + document.getElementById('#search').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("No Match");
                    }
                });
            }
        });
    }

你需要给li一个动态id

<li id="li_@item.Index">

并在过滤函数中隐藏所有 li 项在 ul 下, 然后循环结果以显示所选项目

在控制器中:

public ActionResult Index()
{           
    return View();
}
  
public JsonResult Refresh(string search)
{               
    return Json(Records(search), JsonRequestBehavior.AllowGet); 
}
 
private List<DocumentViewModel> Records(string search)
{
    var list = /* your code to obtain records */; 
    return (String.IsNullOrEmpty(search)) ? list : list.Where(r => r.Title.StartsWith(search)).ToList();
}

Index.cshtml:

@* 
  There is no data model here - the jQuery is working excellent for this example.
*@
<!DOCTYPE html>

<script>
    window.onload = function () {
        Refresh();
    }

    function Refresh() {
        var search = document.getElementById("search").value;
        $.ajax({
            type: "GET",
            url: '@Url.Action("Refresh", "Home")',
            contentType: "application/json;charset=utf-8",
            data: { search },
            dataType: "json",
            success: function (data) {
                $('#menuList').empty();
                for (var i = 0; i < data.length; i++) {
                    $('#menuList').append('<li><div style="display:inline-block; min-width:15%">'
                        + data[i].Index + '</div>'
                        + '<div style="display:inline; min-width:80%">' + data[i].Title + '</div></li>'
                    );
                }
            }
        });
    };
</script>

<html>
<body>
    <div>
        <input id="search" type="text" placeholder="Search Sections" onkeyup="Refresh()">
        <ul id="menuList" style="max-height: 800px; overflow:scroll;">           
        </ul>
    </div>
</body>
</html>