CRich
CRich

Reputation: 57

Sorting a HTML table using Search Keyword?

I have my table displaying, searching, and sorting correctly. But when I search a keyword and display the records in my table and click the column header to sort, the search results gets cleared and I always get brought back to the original page instead of sorting the results of my search. I don't understand why is that happening? Any help would be greatly appreciated. Thank You

Controller:

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());
}

View:

@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>
}

Upvotes: 1

Views: 100

Answers (1)

haim770
haim770

Reputation: 49105

When sorting, you need to pass the keyword parameter as well.

First, pass it from the action to the view:

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

    // ...
}

Then in your View:

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

Upvotes: 1

Related Questions