我的问题是,当我翻到第二页时,搜索字符串“丢失”了,所以我显示的不是一组过滤的结果,而是所有记录。
我的 index.cshtml:
@using (Html.BeginForm("Index", "", FormMethod.Get))
{
<p>
@Html.TextBox("searchString", ViewBag.currentFilter as string, new { @placeholder = "Search by title or author" })
<input type="submit" value="Search" />
</p>
}
@if (Model.PageCount > 1)
{
@Html.PagedListPager( Model, page => Url.Action("Index", new { page }) )
}
我的控制器:
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.TitleSortParm = sortOrder == "Title" ? "Title desc" : "Title";
ViewBag.AuthorSortParm = sortOrder == "Author" ? "Author desc" : "Author";
ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.currentFilter = searchString;
var Articles = from a in db.Articles
select a;
if (!String.IsNullOrEmpty(searchString))
{
//page = 1;
Insights = Articles.Where(s => s.Title.ToUpper().Contains(searchString.ToUpper())
|| s.Author.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "Author":
Insights = Articles.OrderBy(s => s.Author);
break;
case "Author desc":
Insights = Articles.OrderByDescending(s => s.Author);
break;
case "Title":
Insights = Articles.OrderBy(s => s.Title);
break;
case "Title desc":
Insights = Articles.OrderByDescending(s => s.Title);
break;
case "Date":
Insights = Articles.OrderBy(s => s.DatePublished);
break;
default:
Insights = Articles.OrderByDescending(s => s.DatePublished);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(Articles.ToPagedList(pageNumber, pageSize));
}
当我以第 2 页为例时,我的所有变量 sortOrder、currentFilter 和 searchString 都为空。
罗比