开发者

Reverse sort with MVC3 Ajax WebGrid

I want to apply sorting over Ajax, I managed to send the sort column name to my Controller and perform the orderby query in my database, can anyone tell me how can I send the sort order too?

View

<div id="grid">
@{
    var grid = new WebGrid(canPage: true, rowsPerPage: Ctrl.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
    grid.Bind(Model.Events, rowCount: Model.TotalRecords, autoSortAndPage: false);

    grid.Pager(WebGridPagerModes.All);
    @grid.GetHtml(htmlAttributes: new { id="grid" },
            columns: grid.Columns(
            grid.Column("Date"),
            grid.Column("Type"),
            grid.Column("Message")
}
</div>

Controller

public ActionResult Index(int? page, string sort)
{
    var events = GetCollection();
    var startPage = 0;
    var result = new EventListModel();
    if (page.HasValue && page.Value > 0)
    {
        startPage = page.Value - 1;
    }

    result.TotalRecords = events.Count();

    switch (sort)
    {
        case "Type":
            result.Events = events.FindAll().OrderBy(p => p.Type).Skip(startPage * PageSize).Take(PageSize).ToList();
            break;
        case "Message":
            result.Events = events.FindAll().OrderBy(p => p.Message).Skip(startPage * PageSize).Take(PageSize).ToList();
开发者_如何学Go            break;
        case "Date":
            result.Events = events.FindAll().OrderBy(p => p.Date).Skip(startPage * PageSize).Take(PageSize).ToList();
            break;
    }
    return View(result);
}


You could use the sortdir parameter whose possible values will be ASC and DESC:

public ActionResult Index(int? page, string sort, string sortdir)
{
    ...
}

So you could test in the controller action the value of the parameter and perform the corresponding OrderBy or OrderByDescending.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜