我正在学习asp.net mvc 4并按照Contoso大学的教程进行操作,我是第10部分的第3部分。http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
问题我特别关注过滤部分。我注意到,当我有一个搜索字符串并点击搜索时,它会给我我想要的结果。但是,当我单击姓氏或注册以对结果进行排序时,它将为我提供包括所有学生的排序列表。以下是Controller代码:
public ViewResult Index(string sortOrder, string searchString)
{
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
var students = from s in db.Students
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s =>s.LastName.ToUpper().Contains(searchString.ToUpper())
|| s.FirstMidName.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default:
students = students.OrderBy(s => s.LastName);
break;
}
return View(students.ToList());
}
当我处于调试模式时,我注意到即使搜索框中仍然包含原始搜索字符串,传入控制器的Index()d的searchString也为null。如何更改代码以便我可以对筛选结果进行排序?谢谢!
答案 0 :(得分:0)
将过滤器保存到ViewBag并更新排序链接以包含过滤器
ViewBag.CurrentFilter = searchString;
@Html.ActionLink("Last Name", "Index", new { sortOrder=ViewBag.NameSortParm, searchString=ViewBag.CurrentFilter })