0

Since MVC3 WebGrid sorting default is ascending via query string, &sortdir=ASC.. I would like to know how to sort initially by descending.

I've tried below, using Request.QueryString, but in the case were there is absolutely no query string "?..", this doesn't see, to be working:

// Force a descending sort on page load when query string is empty
if(Request.QueryString[grid.SortDirectionFieldName].IsEmpty()){
    grid.SortDirection = SortDirection.Descending;
}

Since I have a path like ..Admin/Review initially, and not ../Admin/Review?sort=Question6&sortdir=ASC, how can I test this case? Would the above condition still return true if there isn't even a query parameter?

I believe I need to extract a query from the raw url and if it doesn't exist, set my sort direction to descending.

tereško
  • 58,060
  • 25
  • 98
  • 150
Ben Sewards
  • 2,571
  • 2
  • 25
  • 43

3 Answers3

3

You may need to change your if statement to this:

 if( string.IsNullOrEmpty(Request.QueryString[grid.SortDirectionFieldName]) ){
     //sort desc
 }
Justin Self
  • 6,137
  • 3
  • 33
  • 48
  • after first sort, it is still sorting ascending. If i change the logic to say !string.isnullorempty, i get by descending, but then it keeps sorting the same way.. – Ben Sewards Oct 26 '12 at 20:16
  • looks like i need to change the query parameter to DESC after some point – Ben Sewards Oct 26 '12 at 20:24
1

Would this work? It will default to Descending unless the querystring variable is explicitly "ASC".

        if (Request.QueryString[grid.SortDirectionFieldName] == "ASC")
        {
            grid.SortDirection = SortDirection.Ascending;
        }
        else
        {
            grid.SortDirection = SortDirection.Descending;
        }
Slippery Pete
  • 3,051
  • 1
  • 13
  • 15
  • this logic is how web grid initially works on click of first sort. I want to sort descending, but the query string is always returning ASC for some reason – Ben Sewards Oct 26 '12 at 20:20
0

ended up using JS:

$(document).ready(function () {
    var ignoreURL = window.location.href.replace('DESC', 'ASC');
    $('#grid th a').each(function () {
        if (this.href.indexOf('ASC') > -1 && this.href != ignoreURL) {
            this.href = this.href.replace('ASC', 'DESC');
        }
    });
});
Ben Sewards
  • 2,571
  • 2
  • 25
  • 43