3

I should add sorting order icons to Ajax WebGrid. The following approach works:

grid.Column("Name", string.Format("Name {0}", grid.SortColumn == "Name" ? grid.SortDirection == SortDirection.Ascending ? "▼" : "▲" : "")

But should be applied to every column.

Is there any other approach to add sorting indicators only to sorted column in one place? For example, modifying the grid after grid.GetHtml().

user1894689
  • 33
  • 1
  • 3

2 Answers2

1

You have already found the only way using the WebGrid API. However, you can apply sorting arrows after the fact using jQuery. You can use hidden fields to store the WebGrid.SortDirection and WebGrid.SortColumn values. Then you can use the ajaxUpdateCallback parameter to specify a function that is called after the grid has been updated asynchronously, and within that method, set the arrows based on the hidden field values:

function setArrows() {
    var dir = $('#dir').val(); //hidden field value
    var col = $('#col').val(); //hidden field value
    var header = $('th a[href*=' + col + ']');
    if (dir == 'Ascending') {
        header.text(header.text() + ' ▲');
    }
    if (dir == 'Descending') {
        header.text(header.text() + ' ▼');
    }
};

I have just written an article about this.

Mike Brind
  • 28,238
  • 6
  • 56
  • 88
0

I found this bit of code handy. You just place it after grid.GetHtml:

@{
   if(!string.IsNullOrWhiteSpace(grid.SortColumn))
   {
    <script type="text/javascript">
     $('thead > tr > th > a[href*="sort=@grid.SortColumn"]').parent().append('@(grid.SortDirection == SortDirection.Ascending ? "▲" : "▼")');
     </script>
   }
}

http://shahvaibhav.com/how-to-add-up-down-arrows-to-webgrid-header-in-razor-mvc-or-sort-indicator-in-webgrid-razor/

Matthew Lock
  • 13,144
  • 12
  • 92
  • 130