0

我正在学习 asp.net mvc 4 并遵循 Contoso 大学教程,我在第 3 部分,共 10 部分。http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/sorting -在-an-asp-net-mvc-应用程序中使用实体框架进行过滤和分页

我的问题特别是关于过滤部分。我注意到当我有一个搜索字符串并单击搜索时,它会给我想要的结果。但是当我单击姓氏或注册对结果进行排序时,它会给我一个包括所有学生的排序列表。以下是控制器代码:

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 为空。如何更改代码以便对过滤结果进行排序?谢谢!

4

1 回答 1

0

将过滤器保存到 ViewBag 并更新您的排序链接以包含过滤器

ViewBag.CurrentFilter = searchString;

@Html.ActionLink("Last Name", "Index", new { sortOrder=ViewBag.NameSortParm, searchString=ViewBag.CurrentFilter })
于 2013-08-20T22:18:34.840 回答