Home > OS >  How to add a search bar to layout.html so that it is processed in the controller?
How to add a search bar to layout.html so that it is processed in the controller?

Time:08-19

I am trying to make the search accessible from anywhere in the application and processed by the usual method of action in the controller. I really need your help.

the method of action in the "Home" 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

CodePudding user response:

You can use the ViewData dictionary for this.

ViewData["searchTerm"] = searchTerm;

//Then reference this anywhere in the cshtml

@ViewData["searchTerm"]

CodePudding user response:

If you want to pass data from controller to view, You can use ViewData["xx"],ViewBag.xx or TempData["xx"].

You can refer to this link to learn more about how use them and the different between them.

  • Related