简体   繁体   English

如何在 layout.html 中添加搜索栏,以便在 controller 中处理?

[英]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.xxTempData["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.

相关问题 如何在C#摘要中包含html标记,以便将其作为文本处理(未解析为XML)? - How do I include an html tag in a C# summary so that it is processed as text (not parsed as XML)? 如何在窗口标题栏中添加一个额外的按钮,这样它将作为标准工作? - How to add an extra button to the window title bar, so it will be work as standard? MVC框架如何处理异步控制器动作? - How are asynchronous controller actions processed by the MVC framework? 如何延迟“热”任务以使它们能够按固定顺序进行处理 - How to delay 'hot' tasks so they can processed in a set order 搜索栏没有找到 MVC 中 Controller 中的动作 - Search bar does not find the action in the Controller in MVC 在统一编辑器中将搜索添加到收藏夹栏 - Add search into favorites bar in unity editor 如何通过控制器将类添加到html元素? - How can I add a class to an html element through a controller? 如何在 WebBrowser 控件中获取呈现的 html(由 Javascript 处理)? - How to get rendered html (processed by Javascript) in WebBrowser control? 在生成html时,是否可以在后端添加'onchange'html / js事件? 如果是这样,怎么样? - Is it possible to add the 'onchange' html/js event in backend when generating html? If so, how? 如何更新进度条以使其顺利增加? - How to update a progress bar so it increases smoothly?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM