我正在关注www.asp.net上的教程,并且我已经尝试对结果表进行排序了。但是,一旦我点击链接命令他们排序,它就不会排序。任何人都可以帮忙吗?
控制器:
public ActionResult Index(string sortOrder)
{
ViewBag.FirstNameSortParm = String.IsNullOrEmpty(sortOrder) ? "firstName_desc" : "";
ViewBag.MiddleNameSortParm = String.IsNullOrEmpty(sortOrder) ? "middleName_desc" : "";
ViewBag.LastNameSortParm = String.IsNullOrEmpty(sortOrder) ? "lastName_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
var students = from s in db.Students
select s;
switch (sortOrder)
{
case "firstName_desc":
students = students.OrderByDescending(s => s.FirstName);
break;
case "middleName_desc":
students = students.OrderByDescending(s => s.MiddleName);
break;
case "lastName_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(db.Students.ToList());
}
查看:
<table class="table">
<tr>
<th>
@Html.ActionLink("First Name", "Index", new { sortOrder = ViewBag.FirstNameSortParm })
</th>
<th>
@Html.ActionLink("Middle Name", "Index", new { sortOrder = ViewBag.MiddleNameSortParm })
</th>
<th>
@Html.ActionLink("Last Name", "Index", new { sortOrder = ViewBag.LastNameSortParm })
</th>
<th>
@Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSortParm })
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.MiddleName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EnrollmentDate)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
@Html.ActionLink("Details", "Details", new { id=item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
答案 0 :(得分:0)
自己发现了这个问题。问题在于这行代码:
return View(db.Students.ToList());
答案应该是:
return View(students.ToList());
这是因为我从数据库中检索我的结果,告诉程序对名称进行排序,然后我返回数据库中的名称,而不是返回包含排序说明的对象学生。