Search code examples
c#asp.net-mvc-3webgrid

MVC 3 WebGrid.Table footer parameter


I've been trying to use the WebGrid to display a footer row that contains totals for the grid. So far, I've been appending the totals row to the result set, which partially works. My issue is that when you sort, the total row also gets sorted, which I don't want. Also, when you add paging in the mix, the total row is in the last page.

I noticed that there is the method WebGrid.Table which takes in a parameter named footer of type System.Func. I'm thinking this might allow me to set the footer row, but there doesn't seem to be any documentation out there on how to use this. How can this be used?


Solution

  • The footer parameter expects a Razor template just like the format parameter of a WebGridColumn:

    var grid = new WebGrid(Model);
    var cols = new List<WebGridColumn>();
    //add some columns
    var table = grid.Table(columns: cols, footer: @<text>Footer</text>);
    ....
    ....
    @table
    

    This will render the word "Footer" in a tfoot element that has a single td with a colspan equal to the number of columns in the List<WebGridColumn>. If you want to align footer text under certain columns, you can pass a full HMTL table in to the Razor template delegate and style it accordingly to achieve the desired alignment eg:

    footer: @<table><tr><td colspan="3">&nbsp;</td><td>footer</td><td>&nbsp;</td></tr></table>
    

    Alternatively, you can use jQuery to create a footer:

    <script>
        $(function () {
            var html = '<tfoot><tr><td colspan="3">&nbsp;</td><td>footer</td><td>&nbsp;</td>';
            $('table').append(html);
        });
    </script>