I need some help in getting the table headers to sort the data populated to a table in MVC. I have implemented search functionality in which the user can filter whatever results by typing a name, but I need to also get the table headers to sort the information as well. I have found similar answers on other sites but when trying to apply them, nothing works. The table headers appear as links but don't sort anything when clicked.
I'm not sure what I'm doing wrong.
(Please ignnore the commented out stuff, I'm trying different approaches)
The current code I have is:
For my Index.cshtml
<div style="height: 200px; overflow: auto;">
<table class="table">
<tr>
<th>
<!--@*@Html.DisplayNameFor(model => model.Title)*@-->
@Html.ActionLink("Title", "Index", new{sortBy=ViewBag.NameSort})
</th>
<th>
<!--@*@Html.DisplayNameFor(model => model.ReleaseDate)*@-->
@Html.ActionLink("ReleaseDate", "Index", new { sortBy = ViewBag.DescSort})
</th>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Actor)
</th>
<th>
@Html.DisplayNameFor(model => model.Actress)
</th>
<th>
@Html.DisplayNameFor(model => model.Rating)
</th>
<th></th>
</tr>
</div>
For my controller the following code is:
public ActionResult Index(string search, string searchBy, string sortBy)
{
var movies = from m in db.Movies select m;
//var sortm = db.Movies.AsQueryable();
//tried this didnt work
if (!String.IsNullOrEmpty(search))
{
movies = movies.Where(s => s.Title.Contains(search));
}
ViewBag.NameSortParm = String.IsNullOrEmpty(sortBy) ? "Title_desc" : "";
ViewBag.DateSortParm = sortBy == "ReleaseDate" ? "ReleaseDate_desc" : "ReleaseDate";
var sortm = from sr in db.Movies select sr;
switch (sortBy)
{
case "Title_desc":
sortm = sortm.OrderByDescending(sr => sr.Title);
break;
case "ReleaseDate_desc":
sortm = sortm.OrderByDescending(sr => sr.ReleaseDate);
break;
case "ReleaseDate":
sortm = sortm.OrderBy(sr => sr.ReleaseDate);
break;
default:
sortm = sortm.OrderBy(sr => sr.Title);
break;
}
return View(db.Movies.ToList());
}
Also if anyone could provide a starting point as to how to get a list of any Actors/Actresses in any genre to display in either the same table list or another in the same page when user clicks on a genre??
Any help is appreciated, thank you.