如何在Mvc中显示应用程序的每页中的搜索框

How to display Search Box in Every Page of the application in Mvc

本文关键字:搜索 显示 Mvc 应用程序      更新时间:2023-09-26

我想在应用程序的每个页面中显示搜索框。我尝试在布局中使用"渲染为局部视图"。但它不起作用。请任何机构建议

/搜索控制器代码:/

 public class SearchController : Controller
    {
       // Filtering the Search with product name
        public ActionResult SearchProduct(string SearchString)
        {
            FlipcartDBContext db = new FlipcartDBContext();
            var products = from p in db.Products select p;
            products = products.Where(s => s.ProductName.StartsWith(SearchString));
            return View(products);
             }

        // Return a Json Result
        public JsonResult GetProducts(string term)
        {
            FlipcartDBContext db = new FlipcartDBContext();
            List<string> products;
     products = db.Products.Where(s=>s.ProductName.StartsWith(term)).Select(x=>x.ProductName).ToList();
            return Json(products, JsonRequestBehavior.AllowGet);
        }
    }

/SearchProduct.cshtml:/

           jQuery(function ($) {
              $("#SearchString").autocomplete({
                                    source: '@Url.Action("GetProducts","Search")',
                                    minLength: 2,
                                });
                            });


        @using (Html.BeginForm())
        {
        <p>
            @Html.TextBox("SearchString", null, new { id = "SearchString" }) <br />
            <input type="submit" value="Search" id="Search" />
        </p>
    }

/*显示产品*/

     @foreach(var item in Model)
            {
                <table>
                    <tr>
                        <td>/* Displaying Selected Product Detail */
                            @Html.DisplayFor(modelItem => item.ProductName)
                        </td>
                        <td>
              <a href="@Url.Action("Details","Store",new{id=item.PkProductID})">here</a>
</td>
           </tr>
        </table>.

/请建议,我是jquery和mvc的新手。提前感谢/

将具有一个名为SearchString的属性的视图模型绑定到局部视图更换

@using (Html.BeginForm()) 

带有

@model viewModel
@using (Html.BeginForm(actionName, contollerName, FormMethod.Post, new { id = id }))    
{
@Html.TextBoxFor(model=>model.SearchString)
<input type='submit'/>
}

其中

controllerName是SearchController

actionName是SearchProduct

并且在SearchProduct方法/操作中将SearchString替换为viewModel