Search code examples
c#jqueryasp.net-mvcrazor

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


I want to do a live search to filter results as I type in the textbox. There is a html Unordered list that is populated from the model when the page is loading and those are the items I want to filter when searching. Problem is how do I update the ul with the search values?

The cshtml page:

<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>

The ajax call:

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

                });
            });
        });

The controller method that query's the db and returns a list that I use to update the model, this works well.

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);
        }

Solution

  • In the controller:

    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();
    }
    

    The 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>