The ASP.NET Web Pages/Razor WebGrid
helper lets you enable paging just by setting the rowsPerPage
property:
var grid = new WebGrid(source: selectedData, rowsPerPage: 3);
Sometimes you want to be able to both to page and to filter the items that are displayed by the WebGrid
helper. Here’s an example from the tutorial I posted on the http://asp.net/web-pages site a couple of weeks ago:
The typical (?) approach here is to create a <form>
element and set its method
attribute to post
:
<form method="post">
<div>
<label for="searchGenre">Genre to look for:</label>
<input type="text" name="searchGenre" value="" />
<input type="Submit" value="Search Genre" /><br/>
(Leave blank to list all movies.)<br/>
</div>
</form>
In the page’s code, you create an is(IsPost)
block in which you set up a parameterized SQL query and run that:
@{
var db = Database.Open("WebPagesMovies") ;
var selectCommand = "SELECT * FROM Movies";
var searchTerm = "";
if(IsPost && !Request.QueryString["searchGenre"].IsEmpty() ) {
selectCommand = "SELECT * FROM Movies WHERE Genre = @0";
searchTerm = Request.QueryString["searchGenre"];
}
var selectedData = db.Query(selectCommand, searchTerm);
var grid = new WebGrid(source: selectedData, rowsPerPage:3);
}
This works great—for the first page. But if you use the page navigation to go to the second page, the grid forgets all about your filter.
The problem is that paging in the grid is implemented as a query string. Note that if you go to page 2, the URL changes to something like this:
http://localhost:45661/Movies?page=2
This means that the URL of the page has changed, which means that the browser is doing a GET. Doing a GET means that your posted form data is ignored.
The fix (a fix) is relatively simple: instead of using the POST
method for the form, use a GET
method:
<form method="get">
<!-- etc -->
</form>
This change causes the form to post the form values in the URL:
http://localhost:45661/Movies.cshtml?searchGenre=Drama&page=2
Then in your page logic, you forget about the IsPost
test and just do this:
if(!Request.QueryString["searchGenre"].IsEmpty() ) { // etc }
With this change, your filter form and the WebGrid
helper’s paging logic work together quite nicely.