2016-01-09 75 views
1

我一直在尝试对项目实施排序并遇到困难。我已经看过如何实现这一点的各种参考,但它仍然不能在我的项目中工作。我已经看过MVC5排序和过滤

http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

http://www.c-sharpcorner.com/UploadFile/4b0136/perform-paging-searching-sorting-in-Asp-Net-mvc-5/

我有我的控制器

public ActionResult Index(string sortBy, string searchString) 
    { 
     ViewBag.NameSortParm = String.IsNullOrEmpty(sortBy) ? "Surname desc" : ""; 
     ViewBag.DateSort = sortBy == "StartDate" ? "date desc" : "StartDate"; 
     var students = from s in db.Students 
         select s; 
     if (!String.IsNullOrEmpty(searchString)) 
     { 
      students = students.Where(s => s.Surname.Contains(searchString)); 
     } 

     switch (sortBy) 
     { 
      case "name_desc": 
       students = students.OrderByDescending(s => s.Surname); 
       break; 
      case "Date": 
       students = students.OrderBy(s => s.StartDate); 
       break; 
      case "date_desc": 
       students = students.OrderByDescending(s => s.StartDate); 
       break; 
      default: 
       students = students.OrderBy(s => s.Surname); 
       break; 
     } 

     return View(db.Students.ToList()); 
    } 

和我的观点

@using (Html.BeginForm()) 
{ 
    <p> 
     Find by name: @Html.TextBox("SearchString") 
     <input type="submit" value="Search" /> 
    </p> 
} 
<table class="table"> 
    <tr> 

     <th> 
      @Html.DisplayNameFor(model => model.Name) 
     </th> 
     <th> 
      @Html.ActionLink("Surname", "Index", new { sortBy = ViewBag.NameSortParm}) 
     </th> 
     <th> 
      @Html.ActionLink("Enrollment Date", "Index", new { sortOrder = ViewBag.DateSort}) 
     </th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.Name) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Surname) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.StartDate) 
     </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> 

这给了我视图中的动作链接,以及在localhost:5841/students?sortBy = Surname%20desc和localhost:5841/students?sortOrder = StartDate上单击的权利。我的问题是,他们不应该改变和排序。我错过了什么吗?

感谢

回答

1

你做的控制器的方法排序,但你最后只是回到使用

return View(db.Students.ToList()); 

再次调用数据库的无序集合。相反,将return语句更改为

return View(students); // or students.ToList() depending on the model in the view 

返回已排序的集合。

+0

Ahhhhhh没有办法真棒,谢谢斯蒂芬 – MarkJClark