[英]How to add a search bar to layout.html so that it is processed in the controller?
I am trying to make the search accessible from anywhere in the application and processed by the usual method of action in the controller.我试图使搜索可以从应用程序中的任何位置访问,并通过 controller 中的常用操作方法进行处理。 I really need your help.我真的需要你的帮助。
the method of action in the "Home" controller: “首页”controller中的操作方法:
public IActionResult Index(string searchTerm)
{
return View((!string.IsNullOrEmpty(searchTerm))
? repository.Products.Where(
c => c.Name.ToLower().Contains(searchTerm.ToLower())).ToList()
: RedirectToAction(nameof(ManList)));
}
Going deeper, I'm trying to pass the string searchTerm
to layout to use it in (this is how it works in the Index view), but I have no idea how to do it更深入地讲,我试图将字符串searchTerm
传递给布局以使用它(这是它在索引视图中的工作方式),但我不知道该怎么做
You can use the ViewData
dictionary for this.您可以为此使用ViewData
字典。
ViewData["searchTerm"] = searchTerm;
//Then reference this anywhere in the cshtml
@ViewData["searchTerm"]
If you want to pass data from controller to view, You can use ViewData["xx"]
, ViewBag.xx
or TempData["xx"]
.如果要从 controller 传递数据进行查看,可以使用ViewData["xx"]
、 ViewBag.xx
或TempData["xx"]
。
You can refer to this link to learn more about how use them and the different between them.您可以参考此链接以了解有关如何使用它们以及它们之间的区别的更多信息。
You can use asp.net core ViewComponent
to solve this problem.可以使用asp.net核心ViewComponent
来解决这个问题。 A view component has its own view and backend logic and can be invoked anywhere from the application eg controllers or views.视图组件有自己的视图和后端逻辑,可以在应用程序的任何地方调用,例如控制器或视图。
You can have a better idea about how view components work by following the article: View components in ASP.NET Core您可以通过以下文章更好地了解视图组件的工作原理: 在 ASP.NET 内核中查看组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.