【问题标题】:Search and filter in list ASP.NET MVC在列表 ASP.NET MVC 中搜索和过滤
【发布时间】:2019-11-03 09:30:57
【问题描述】:

我正在尝试在我的列表中实现搜索,但由于某种原因,它不起作用。我使用 jQuery 脚本进行搜索 - 请指导我。

这是我的控制器和我的视图:

public ActionResult Details(int S)
{
    SLMEntitiesDB dbContext = new SLMEntitiesDB();

    var VL = (from U in dbContext.Users
              join P in dbContext.Products on U.PID equals P.PID
              where P.PID == U.PID
              select new UP()
                         {
                             UserO = U,
                             ProductO = P
                         }).Where(U => U.UserO.LID == S).ToList();

    ViewBag.result = VL;

    return View(ViewBag.result);
}

查看

    @model IEnumerable<SLMDemo0.Models.UP>
    <input type="text" id="txtsearch" placeholder="Search"/>    
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.UserO.UserName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.ProductO.PName)
            </th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.UserO.UserName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.ProductO.PName)
                </td>
               <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.UserO.UID })
    </table>
    <script src="~/Scripts/jquery-3.3.1.min.js"></script>
    <script>
        $("txtsearch").on("keyup", function () {
            var txtenter = $(this).val();
            $("table tr").each(function (results) {
                if (results !== 0) {
                    var id = $(this).find("td:nth-child(2)").text();
                    if (id.indexOf(txtenter) !== 0 && id.toLowerCase().indexOf(txtenter.toLowerCase()) < 0) {
                        $(this).hide();
                    }
                    else {
                        $(this).show(); } } }); }); </script>

代码没有结果,我可以查看列表中的内容,但是当您在搜索中键入任何内容时,什么都没有发生。

【问题讨论】:

  • 您应该返回View(result); 开始。
  • 如果列表被渲染,那么你的选择器$("#txtsearch")中缺少#

标签: sql asp.net-mvc entity-framework


【解决方案1】:

您错过了$("txtsearch") 中的# 标识符 请与$("#txtsearch")一起使用

<script>
    $("#txtsearch").on("keyup", function () {
        var txtenter = $(this).val();
        $("table tr").each(function (results) {
            if (results !== 0) {
                var id = $(this).find("td:nth-child(2)").text();
                if (id.indexOf(txtenter) !== 0 && id.toLowerCase().indexOf(txtenter.toLowerCase()) < 0) {
                    $(this).hide();
                }
                else {
                    $(this).show(); } } }); }); </script>

【讨论】:

  • 添加缺失的#后,每当我在搜索中输入任何内容时,所有记录都会被清除/消失。
  • 请参考这个link,我用过你的js,效果很好
猜你喜欢
  • 1970-01-01
  • 2022-11-28
  • 2017-08-20
  • 1970-01-01
  • 1970-01-01
  • 2010-10-24
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多