I wanted to make a search text field in my layout page so searching would be available all over the website. The issue is that it works well in controller but does not work while working on layout (probably routing is bad because it adds "?searching" to any subpage and does not redirect to correct controller and action).
_Layout.cshtml
@using (Html.BeginForm("Search", "Home", FormMethod.Get ))
{
@Html.TextBox("searching")
<input type="submit" value="Search" placeholder = "Search" />
}
HomeController.cshtml
public ActionResult Search(string searching)
{
IEnumerable<Book> books = from t in Book.allBooks select t;
if (!String.IsNullOrEmpty(searching))
{
books = books.Where(a => a.Title.ToLower().Contains(searching.ToLower()));
}
return View(books.ToList());
}
View = Search.cshtml
@model IEnumerable<LibraryMVC.Core.Models.Book>
@{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 style="margin-top: 30px">Results for: </h2>
<hr style="max-width:500px;" />
<div class="container" style="padding-bottom:60px; display: flex; margin: 0px; font-size: 20px; padding-top: 10px; max-width:100%;">
<div class="row" style="width: 100%; justify-content: center; margin-left: 0px">
@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
@Html.TextBox("searching")
<input type="submit" value="Search" />
}
@if (Model.Count() == 0)
{
<h2 style="margin-top: 30px">Book have not been found</h2>
}
else
{
foreach (var item in Model)
{
<div class="col-12 col-md-6 col-lg-6 col-xl-3 align-items-center" style="margin-top: 10px; margin-bottom: 10px;">
<div class="col-md-12 d-flex justify-content-center">
<img src="~/Content/BookImages/@item.Image" class="img-thumbnail" style="height: 400px; width: 250px;" />
</div>
<div class="col-md-12 text-center">
<strong>@Html.ActionLink(item.Title, "Details", "Home", new { id = item.Id }, null)</strong>
</div>
<div class="col-md-12 text-center">
@item.WriterFirstName
</div>
<div class="col-md-12 text-center">
@item.WriterLastName
</div>
</div>
}
}
</div>
</div>
Please help. Thank you