I'm implementing sorting for a table in my view, where it gets populated through ajax calling JsonResult
method
this is the header link I use for ordering:
<a style="cursor: pointer" onclick="getData('@Html.Raw(ViewBag.Sort == "asc" ? "desc" : "asc")')" id="sort">Title</a>
the JsonResult
method:
public JsonResult BooksData(string sort)
{
ViewBag.Sort = ViewBag.Sort == "desc" ? "asc" : "desc";
var books = new List<Book>();
if (sort == "asc")
{
books = db.Books.Include(b => b.Author).OrderBy(b => b.Title).ToList();
ViewBag.Sort = "desc";
}
else
{
books = db.Books.Include(b => b.Author).OrderByDescending(b => b.Title).ToList();
ViewBag.Sort = "asc";
}
return Json(books, JsonRequestBehavior.AllowGet);
}
the getsData
function:
function getData(sort) {
var srt = sort;
$('#tbl>tbody').empty();
$.ajax({
type: 'GET',
url: '/Book/BooksData?sort=' + srt,
dataTtype: 'json',
success: function (data) {
$.each(data, function (index, val) {
$('#tbl>tbody').append('<tr><td>' + val.Title + '</td><td>' + val.Author.Name + '</td></tr>')
});
}
});
}
but the value of ViewBag.Sort
is always asc
?