2016-01-09 72 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