Search code examples
asp.net-mvc-3razorwebgrid

Sorting with WebGrid


I am creating a WebGrid and am trying to enable sorting. Actually, sorting works but I notice that you can only sort on columns where the columnName is not blank in the grid.columns call. So in my example I have this:

@grid.GetHtml(
    columns: grid.Columns(
        grid.Column(columnName: "", header: "Item title", format: @<text> @GetItemTitle(@item.InventoryReference) </text>),
        grid.Column(columnName: "OwnerReference", header: "Owner reference")
     )
);

In this exampple, Item title is not sortable but Owner reference is. The quesiton is, how do I get Item title to be sortable and why does this happen?


Solution

  • For columns where you have used custom format you will have to do the sorting yourself. So you will have to give your custom column a name which will be used for identifying it on the server:

    grid.Column(
        columnName: "title", 
        header: "Item title", 
        format: @<text> @GetItemTitle(@item.InventoryReference) </text>
    ),
    

    and the header of this column is clicked a query will be sent to the controller action that will look like this:

    /controller/action/?sort=title&sortdir=ASC
    

    So inside your controller action you will use this information to sort your data set.

    public ActionResult Foo(string sort, string sortdir)
    {
        // check if sort = title and then sort your dataset accordingly
        // before returning the model to the view
        ...
    }
    

    The reason sorting works for columns for which you haven't defined a custom format is because the WebGrid helper is capable to automatically sort the dataset before displaying it, but that's obviously bad because things like sorting and paging should absolutely be done in your backend layers (like for example in the database if you are using one) in order to have efficient sorting and paging. So even for columns without custom format you should be doing the sorting/paging at the database level instead of relying on the WebGrid helper to sort/page the dataset before displaying.