Displaying Search Results In A WebGrid

4.64 (14 votes)

A number of people have run into problems when trying to combine a search or filter form, and a WebGrid. The main issue that arises is when paging or sorting the search result or a filtered subset of it. Here, I look at the cause of the problem and what you can do about it.

Like other articles in this series, the sample code makes use of a SQL CE 4.0 version of the Northwind database. It is available as part of the download that accompanies this article, a link to which is provided at the end. The sample also makes use of the same layout page as other samples, which references jQuery, and includes a RenderSection call to an optional section called "script":

<!DOCTYPE html>

<html lang="en">
        <meta charset="utf-8" />

        <script src="@Href("~/scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>

        <link href="@Href("~/styles/site.css")" rel="stylesheet" />
        @RenderSection("script", required: false)


The main file in the sample includes a code block at the top, the HTML and Razor markup, and content for the "script" section:

    Page.Title = "Filter WebGrid";
    var db = Database.Open("Northwind");
    var query = "SELECT DISTINCT Country FROM Customers ORDER BY Country";
    var countries = db.Query(query);
    query = "SELECT * FROM Customers  WHERE CompanyName LIKE @0 AND Country LIKE @1";
    var company = "%" + Request["company"] + "%";
    var country = "%" + Request["country"] + "%";
    var data = db.Query(query, company, country);
    var columns = new[]{"CustomerID", "CompanyName", "ContactName", "Address", "City", "Country", "Phone"};
    var grid = new WebGrid(data, columnNames: columns, rowsPerPage: 6);
<h1>Filter WebGrid</h1>
<form method="post">
    <div id="grid">
        Company Name: <input type="text" name="company" value="@Request["company"]" />
        Country: <select name="country">
            @foreach(var item in countries){
                <option @(Request["country"] == item.Country ? " selected=\"selected\"" : "")>@item.Country</option>
        <input type="submit" />
            tableStyle : "table",
            alternatingRowStyle : "alternate",
            headerStyle : "header",
            columns: grid.Columns(
                grid.Column("CustomerID", "ID"),
                grid.Column("CompanyName", "Company"),
                grid.Column("ContactName", "Contact"),
@section script{
<script type="text/javascript">
        $('th a, tfoot a').live('click', function() {
            $('form').attr('action', $(this).attr('href')).submit();
            return false;

The page features a form containing a text box and a select list along with the grid:

By default, the grid is populated by all companies within the database. There are a couple of parameters in the WHERE clause, but the value of the parameters on the first request is %%, which equates to a wildcard match.

The text box allows the user to search for entries based on part of a company name, while the select list allows the user to filter results in the grid by country. The form is POSTed to the server, and therein lies the root of the problem. You can see that sorting and paging links feature are part of the grid. All of these, when clicked, result in GET requests being made, which leaves the form - and its content - behind.

The answer to the problem lies in the snippet of jQuery that appears in the script section. A handler is attached to the onclick event of the links in the table head and table foot areas - or the sorting and paging links. When they are clicked, the value of the link is obtained and provided to the form's action attribute, Then the form is submitted using POST, and the GET request is cancelled by return false. This ensures that paging and sorting information is preserved in the Request.QueryString collection, while any form field values are passed in the Request.Form collection.

A demo containing the source code is available here.


Date Posted:
Last Updated:
Posted by:
Total Views to date: 50676


- 2bitcoder

Great Article - should this work when using ajaxUpdateContainerId?

- reav

i think that it will work better to use Session["value"] feature, here is an example


- Mike


You need to make some changes when using an Update Container. I'll post an article on how to do that shortly.

- Mike


I can't see any good reason to use Session as well as Request in this scenario.

- Alan


Would The Above given code of webform would only work with MVC? Is there a similar control like this for the asp.net v3.5?


- Mike


The WebGrid is only available to Razor Web Pages or Razor Views in MVC. The GridView is the Web Forms table control.

- Sithelo

Thanks for a simple tutorial. Excellent wor.
How do you hide the webgrid and show it when submit is click?

- Splendor


Does the article about using this with an Update Container exist? I can't seem to find anything, but maybe I'm not looking in the right place.

- Raha

Hi Mike
How can I find first part of this tut
Im persian men and i confusing in these a lot of english
so I can Find first part of this tut to begin learning
I 'll be so thanks if you link here first part of this tut
Thanks Mike
Really thanks
with the best ragard:

- Mike


I'm not sure what you mean by "first part". This is a standalone tutorial. Here are other articles that cover the Webgrid though: http://www.mikesdotnetting.com/Category/31

- Beth

hey, Does the Grid and the search box come with a css

Recent Comments

Phil 29/11/2015 18:48
In response to iTextSharp - Working with images
Hi Mike, great article as ever. Any chance you can do an example of adding a swf to a pdf with I it...

makhlas 27/11/2015 17:05
In response to How To Send Email In ASP.NET MVC
hello, thanks for sharing these tutos , but when i apply the send button, i'm gettin this error...

raphael 27/11/2015 13:59
In response to ASP.NET 5: Managing Client-side Dependencies with NPM, Bower and Gulp
i fixed it. i'm not sure *what* it is that VS does, but you get the same result if you do a "npm on...

Raphael 27/11/2015 13:02
In response to ASP.NET 5: Managing Client-side Dependencies with NPM, Bower and Gulp
There seems to be a major issue with the dependency manager in VS2015. I haven't yet figured out but...

Joaquín Bresan 26/11/2015 17:58
In response to Getting the identity of the most recently added record
Great contribution friend. Thank you so much for sharing....

JR 26/11/2015 02:49
In response to ASP.NET MVC 5 with EF 6 - Working With Files
Hello, Where is the location of the database? Thanks...

sumalatha 24/11/2015 22:09
In response to ASP.NET 5 Middleware, Or Where Has My HttpModule Gone?
Great article. I have gone through hundreds of articles, finally this gives the comprehensive of...

TimPat10 24/11/2015 17:35
In response to A Better Way To Export Gridviews To Excel
Great article. I've noticed that date fields have to be re-formatted when the spreadsheet is pulled...

Rajasekar 24/11/2015 12:27
In response to Import Data From Excel to Access with ASP.NET
While use this code i'm facing on error: "Unrecognized Database format C:\mydabase.accdb" can any...

Parmod 24/11/2015 07:28
In response to ASP.NET 5 Project Basics
For a new learner (Fresher) in ASP.NET there is a issue Fresher have to learn two types of , old...