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.
<table>
<tr>
<th>
<a href="@Url.Action("Dispatch", "Calls", new { userName = Session["UserName"], new { sortOrder = "Name_desc" })">Name</a>
</th>
</tr>
</table>
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;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With