Default Sort is not working while using WebGrid He

2019-08-06 04:09发布

问题:

I am using @grid.GetHtml gridview to show the grid in my ASP.NET MVC4 application.

Default Sort is not working while using WebGrid Helper With Column (Primary Key) as hidden.

Using SP to fetch the web grid data and also default sort is given in SP.

My code:

@grid.GetHtml(
    htmlAttributes: new
      {
          id = "XXXX"
      },
    tableStyle: "table table-bordered table-condensed table-hover table-striped",
    headerStyle: "info",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "gridrow",
    columns: grid.Columns(
        grid.Column("AAAA", "AAAA",style:"hidecol") //Primary Column Name is “AAAA” 
    )
)

JQuery Code to hide Column Header of Primary Column.

<script type="text/javascript">
$(document).ready(function() {
  $("# XXXX th:nth-child(1)").hide();
});
</script>

回答1:

You could just sort the items in your controller before passing them to the view. That way they should retain the order you want:

public IActionResult Index()
{
    var items = new List<obj>(){new obj(5), new obj(1), new obj(355)};
    var sortedItems = items.OrderBy(o => o.Id);
    return View(sortedItems);
}

And if you need a way from sorting them in the view itself, you can do something like

public IActionResult Index(string sortOrder)
{
    var items = new List<obj>(){new obj(5), new obj(1), new obj(355)};

    if (sortOrder == "ASC")
    {
        items = items.OrderBy(o => o.Id).ToList();
    }
    return View(items);
}

Where you call that controller from a button or whatever you need in your view