11 July 2017

Sorting a List of Results in ASP.NET MVC 5

Here's a simple example:


Controller 

private ProfileContext db = new ProfileContext();

public ActionResult Index(string sortOrder)
{
    ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name" : "";
    ViewBag.AgeSortParm = sortOrder == "Age" ? "age" : "Age";
   
    var emp = db.Profiles.Select(y => y);
   
    switch (sortOrder)
    {
        case "name":
        emp = emp.OrderByDescending(y => y.Name);
        break;
           
        case "age":
        emp = emp.OrderByDescending(y => y.Age);
        break;
           
        default:
        emp = emp.OrderBy(y => y.Name);
        break;
    }
   
    return View(emp);
}


View

<table class="table">
    <tr>
        <th>
            @Html.ActionLink("Name", "Index", new { sortOrder = ViewBag.NameSortParm })
        </th>
        <th>
            @Html.ActionLink("Age", "Index", new { sortOrder = ViewBag.AgeSortParm })
        </th>      
    </tr>

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

No comments:

Post a Comment