使用 ajax 显示搜索结果

Showing search results using ajax

您好,我正在开发一个简单的 asp.net mvc 应用程序。 我有一个搜索按钮 returns 一个 table 的 Products 。 我把这个 table 放在局部视图中。当我点击搜索按钮时,它会打开另一个页面,我真正想要的是在同一页面上显示搜索结果(table)。 这是 Home Controller

中的搜索方法
      public ActionResult SearchM(string Search)
    {
        var viewMod = new MyViewModel
        {
            ProductsV = DB.Products.Where(x => 
      x.ProductName.StartsWith(Search)).ToList()

        };
        return View(viewMod);
    }
    }

产品部分视图

 @model OnlineShopping.MyViewModel

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>


 <table class="table table-bordered">
<thead>
    <tr>

        <th>Product Name</th>
        <th>Price</th>
        <th>Description</th>
        <th>Product Image</th>

    </tr>
</thead>
@foreach (Product item in Model.ProductsV)
{
    <tr>
        <td>@item.ProductName</td>
        <td>@item.ProductPrice</td>
        <td>@item.ProductDetails</td>
        <td><img src="@Url.Content(@item.ProductImage)" width="120" 
   height="160" /></td>
    </tr>

  }
 </table>

索引视图

   <script>

        $(document).ready(function () {
            $('#SearchMenu').click(function () {
                $('.showSearch').toggle("slide");
            });
        });
  </script>

 <h3>Search:</h3>


 @using (Html.BeginForm("SearchM", "Home", FormMethod.Get))
{

    <label> Search:</label> <input type="text" name="Search" class="btn- 
  block" />
    <br />

    <div id="SearchMenu">
        <input type="submit" value="Search" class="btn-light" />

    </div>

  }


  <div id="showSearch"><input type="button" class="btn-success" 
   value="Show/Hide All Products" /></div><br />
  <div class="SearchMenu" style="display: none;">
    @Html.Partial("SearchM", Model)
  </div>

您可以使用 MVC AJAX 帮助程序或使用 AJAX 调用拦截提交事件。
当您使用 MVC 时,我建议您使用 AJAX 助手。

您需要从 NuGet 包管理器安装 Microsoft.Jquery.Unobtrusive.Ajax 才能使用帮助程序。

一旦你安装了它,它应该就像改变这个一样简单:

@using (Html.BeginForm("SearchM", "Home", FormMethod.Get))

为此:

@using (Ajax.BeginForm("SearchM", "Home", new AjaxOptions() { UpdateTargetId = "SearchMenu" }))