使用MVC3 Ajax WebGrid进行反向排序

时间:2011-04-16 12:33:53

标签: c# asp.net-mvc-3

我想在Ajax上应用排序,我设法将排序列名称发送到我的Controller并在我的数据库中执行orderby查询,有人能告诉我如何发送排序顺序吗?

查看

<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>

控制器

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();
            break;
        case "Date":
            result.Events = events.FindAll().OrderBy(p => p.Date).Skip(startPage * PageSize).Take(PageSize).ToList();
            break;
    }
    return View(result);
}

1 个答案:

答案 0 :(得分:2)

您可以使用sortdir参数,其可能的值为ASCDESC

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

因此,您可以在控制器操作中测试参数的值,并执行相应的OrderByOrderByDescending