Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting fields ascending and descending with single link

So I have a MVC app with a table and when the header is clicked I would like it to switch between sorting in ascending or descending fashion depending how many times it is clicked.

Currently I can only sort descending or ascending I don't know how to implement both. userName is just a variable I'm getting from another controller when a user logs in and I'm using a switch because I plan on having multiple headers that can be sortable.

View

<table>
    <tr>
        <th>
            <a href="@Url.Action("Dispatch", "Calls", new { userName = Session["UserName"], new { sortOrder = "Name_desc" })">Name</a>
        </th>
    </tr>
</table>

Controller

public ActionResult Index(string userName, string sortOrder)
{
    string userName = Session["UserName"].ToString();

    var model = from t in db.Users
                where t.UserName == userName
                select t;

    switch(sortOrder)
    {
        case "Name_desc":
            model = model.OrderByDescending(t => t.UserName);
            break;
    }
}
like image 416
Mr.Smithyyy Avatar asked Nov 19 '15 15:11

Mr.Smithyyy


1 Answers

Put your sort order in a ViewBag value. Check inline (Viewbag.NameSort):

View:

<th>
    <a href="@Url.Action("Dispatch", "Calls", new { userName = Session["UserName"], new { sortOrder = ViewBag.NameSort })">Name</a>
</th>

Controller:

public ActionResult Index(string userName, string sortOrder)
{
    string userName = Session["UserName"].ToString();

    // Convert sort order
    ViewBag.NameSort = sortOrder == "Name" ? "Name_desc" : "Name";

    var model = from t in db.Users
                where t.UserName == userName
                select t;

    switch(sortOrder)
    {
        case "Name_desc":
            model = model.OrderByDescending(t => t.UserName);
            break;
        case "Name":
            model = modelOrderBy(t => t.UserName);
            break;
    }
}
like image 122
Jelle Oosterbosch Avatar answered Jan 03 '23 11:01

Jelle Oosterbosch