【问题标题】:ASP.NET MVC 3 Custom sorting a WebGrid with ascending, descending optionsASP.NET MVC 3 使用升序、降序选项对 WebGrid 进行自定义排序
【发布时间】:2012-04-18 08:35:54
【问题描述】:

嘿嘿, 我正在开发一个 ASP.NET MVC 3 应用程序。

我有一个观点

var grid = new WebGrid(rowsPerPage: 10, ajaxUpdateContainerId: "GridDiv",canPage: true,canSort: true);
grid.Bind(source: Model);
grid.Pager(WebGridPagerModes.All);
@grid.GetHtml(htmlAttributes: new { id="grid" },
    columns: grid.Columns(
    grid.Column("Name"),
    grid.Column("Age"),
    grid.Column("Sex")
)

在控制器中,我有一个自定义的排序算法来对数据进行排序。 我有自定义升序排序和自定义降序排序。

我希望当用户单击列标题时按照我的自定义排序算法而不是内置排序算法对行进行排序。

为此我尝试了以下方法(我采用“sortdir”并相应地处理它)

控制器

public ActionResult Persons(string sortdir)
{    
    PersonsListModel = GetAllPersonsList();
    if(sortdir=="ASC")
        return View(MyAscendingCustomSortAlgorithm(PersonsListModel ));
    else
        return View(MyDescendingCustomSortAlgorithm(PersonsListModel ));
}

MyAscendingCustomSortAlgorithmMyDescendingCustomSortAlgorithm 是返回按我的自定义算法排序的列表的函数。

当页面加载时,列表排序正确,但是当我点击标题时排序混乱。我调试了,一切正常。

我的问题是我怎样才能让它工作,并且仍然保持正确的分页

我也尝试设置canSort: false,但我无法再点击标题。

非常感谢您的帮助

【问题讨论】:

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


【解决方案1】:

您是否尝试过关闭 Bind() 方法中的 autoSortAndPage 参数?

grid.Bind(source: Model, autoSortAndPage : false);

我知道您想保留现有的分页,但我不确定是否有办法同时拥有这两者。您可能需要在您的操作方法中手动进行分页。

【讨论】:

    【解决方案2】:

    你应该这样搜索:

    1. 禁用排序
    2. 向列标题添加自定义样式(.GetHtml html 属性中的“headerStyle: customStyle”)。查看章节Styling your grid
    3. 使用 jquery 为所有具有此样式的元素添加 live 点击处理程序,当用户点击时检查它是哪一列并相应地发布到您的控制器,该控制器将刷新页面

    此外,您可以在 css 中添加一些链接到您的 customStype 的样式,即“光标:手”,以便用户看到标题是可点击的。

    【讨论】:

      【解决方案3】:

      我会在您的方法参数中添加页码、行数、排序列和排序方向。它也应该只返回 json 数据。您应该在 javascript 中处理该数据以更新您的视图。

      您可以将自己的排序 css 类添加到标题并链接到 ajax 操作。可能可以在 javascript 中处理您的网格并只需更改数据行。

      public JsonResult Persons(int pagenumber,int rows, string sortcol, string sortdir)
      {    
      
      if(sortdir=="ASC")
          return DataSource(pagenumber,rows,sortcol,MyAscendingCustomSortAlgorithm);
      else
          return DataSource(pagenumber,rows,sortcol,MyDescendingCustomSortAlgorithm);
      
      }
      

      您可以将排序函数传递给数据源调用并使用它来返回 json 数据。您可以使用 linq 查询来行

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-16
        • 1970-01-01
        • 2014-08-12
        • 2020-06-06
        • 2016-11-05
        • 1970-01-01
        • 1970-01-01
        • 2017-01-31
        相关资源
        最近更新 更多