如何将搜索结果添加到MVC5中的标题



我想在子页面的标题中添加搜索查询名称,例如,如果有人在搜索框中键入John,他/她收到的页面是:Searching results for:John

家庭控制器:

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());
}

_Layout.cshtml:

<li class="d-none d-lg-block justify-content-center" style="align-self: center; padding-right: 10px">
@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
<i class="fas fa-search" aria-hidden="true" style="padding-right: 5px"> </i>
@Html.TextBox("searching")
<input type="submit" value="Search" />
}
</li>

Search.cshtml:

@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
@*@Html.TextBox("searching")
<input type="submit" value="Search" />*@
}
@if (Model.Count() == 0)
{
<h2 style="margin-top: 30px">Not found any book with this name</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>
}
}

感谢您的帮助

这可能适用于您:

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()));
}
ViewBag.SearchTerm = searching;
return View(books.ToList());
}

在你看来:

@using (Html.BeginForm("Search", "Home", FormMethod.Get))
{
@*@Html.TextBox("searching")
<input type="submit" value="Search" />*@
}
@if (Model.Count() == 0)
{
<h2 style="margin-top: 30px">Not found any book with this name</h2>
}
else
{
<h2 style="margin-top: 30px">Search results for: @ViewBag.SearchTerm</h2>
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>
}
}

请注意,这是一个快速而肮脏的解决方案。合适的方法是创建一个ViewModel,并添加图书和搜索词。

public class SearchBookViewModel {
public IEnumerable<Book> Books {get; set;}
public string SearchTerm {get; set;}
}

如果无法更改ViewModel,请使用ViewBag。ViewBag的糟糕之处在于,如果有人更改了控制器中的代码,那么您只能在运行时发现。

最新更新