使用搜索关键字对HTML表格进行排序?

时间:2016-11-30 17:02:31

标签: html asp.net-mvc razor

我的表格正确显示,搜索和排序。但是,当我搜索关键字并在我的表中显示记录并单击列标题进行排序时,搜索结果将被清除,并且我总是被带回原始页面而不是对搜索结果进行排序。我不明白为什么会这样?任何帮助将不胜感激。谢谢

控制器:

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 个答案:

答案 0 :(得分: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>