2016-11-30 43 views
1

我有我的表正確顯示,搜索和排序。但是,當我搜索關鍵字並在我的表格中顯示記錄並單擊列標題進行排序時,搜索結果將被清除,並且我總是會將其帶回原始頁面,而不是對搜索結果進行排序。我不明白爲什麼會發生這種情況?任何幫助將不勝感激。謝謝使用搜索關鍵字排序HTML表格?

控制器:

public ActionResult ViewInventory(string owners, string keyword, string sortOrder) 
     { 
      ViewBag.OwnerSort = sortOrder == "owner_asce" ? "owner_desc" : "owner_asce"; 

      var records = from s in db.Assets select s; 
      switch (sortOrder) 
      { 
       case "owner_asce": 
        records = records.OrderBy(s => s.InventoryOwner); 
       break; 

       case "owner_desc": 
        records = records.OrderByDescending(s => s.InventoryOwner); 
       break; 
      } 
      return View(records.ToList()); 
} 

查看:

@model IEnumerable<CTS_Inventory.Models.Asset> 

@{ 
    ViewBag.Title = "View Inventory"; 
} 

<h2>View Inventory</h2> 


@using (Html.BeginForm()) 
{ 
    <p> 

     Keyword Search: @Html.TextBox("keyword") 

     <input type="submit" value="Search" /> 
    </p> 

    <table class="table" border="1"> 
     <tr> 
      <th> 
       @Html.ActionLink("owners","ViewInventory", new { sortOrder = ViewBag.OwnerSort}) 
      </th> 
     </tr> 

     @foreach (var item in Model) 
     { 
      <tr> 
       <td> 
        @Html.DisplayFor(modelItem => item.InventoryOwner) 
       </td> 
      </tr> 
     } 
    </table> 
} 

回答

1

排序時,您需要通過keyword參數也是如此。

首先,從動作傳遞給視圖:

public ActionResult ViewInventory(string owners, string keyword, string sortOrder) 
{ 
    ViewBag.OwnerSort = sortOrder == "owner_asce" ? "owner_desc" : "owner_asce"; 
    ViewBag.Keyword = keyword; 

    // ... 
} 

然後在您的視圖:

<th> 
    @Html.ActionLink("owners","ViewInventory", new { sortOrder = ViewBag.OwnerSort, keyword = ViewBag.Keyword }) 
</th> 
+0

謝謝!!最後讓它工作。一直困住這個4小時試圖弄清楚。 – CRich