Displaying Search Results In A WebGrid

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">
    <head>
        <meta charset="utf-8" />

        <title>@Page.Title</title>
        <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)
    </head>

    <body>
        @RenderBody()
    </body>
</html>

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">
                 <option></option>   
            @foreach(var item in countries){
                <option @(Request["country"] == item.Country ? " selected=\"selected\"" : "")>@item.Country</option>
            }
        </select>
        <input type="submit" />
        @grid.GetHtml(    
            tableStyle : "table",
            alternatingRowStyle : "alternate",
            headerStyle : "header",
            columns: grid.Columns(
                grid.Column("CustomerID", "ID"),
                grid.Column("CompanyName", "Company"),
                grid.Column("ContactName", "Contact"),
                grid.Column("Address"),
                grid.Column("City"),
                grid.Column("Country"),
                grid.Column("Phone")
            )
        )
    </div>
</form>
@section script{
<script type="text/javascript">
   $(function(){
        $('th a, tfoot a').live('click', function() {
            $('form').attr('action', $(this).attr('href')).submit();
            return false;
        });
    });
</script>
}


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: Saturday, August 27, 2011 4:57 PM
Last Updated: Wednesday, December 19, 2012 8:45 PM
Posted by: Mikesdotnetting
Total Views to date: 34054

11 Comments

Wednesday, August 31, 2011 1:50 PM - 2bitcoder

Great Article - should this work when using ajaxUpdateContainerId?

Thursday, September 1, 2011 6:58 AM - reav

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

http://pastebin.com/KvRFQ45A

Thursday, September 1, 2011 8:06 AM - Mike

@2bitcoder,

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

Thursday, September 1, 2011 8:10 AM - Mike

@reav

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

Thursday, September 1, 2011 9:24 PM - Alan

Hello,

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?

Regards.

Friday, September 2, 2011 7:35 AM - Mike

@Alan

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

Tuesday, February 19, 2013 2:10 PM - Sithelo

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

Tuesday, March 12, 2013 3:16 PM - Splendor

@Mikesdotnetting

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.

Sunday, December 22, 2013 7:59 AM - 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:
Raha

Sunday, December 22, 2013 8:12 AM - Mike

@Raha

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

Tuesday, January 14, 2014 4:12 PM - Beth

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

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Bino 11/27/2014 7:05 PM
In response to MVC 5 with EF 6 in Visual Basic - Async and Stored Procedures with the Entity Framework
Copy +...

Manas 11/27/2014 5:30 AM
In response to Scheduled Tasks In ASP.NET With Quartz.Net
Hi Mike, Thank you for awesome article. My concern is it might impact website if we use or is...

priya 11/26/2014 6:50 PM
In response to Create PDFs in ASP.NET - getting started with iTextSharp
very nice.....its save my time...

ransems 11/24/2014 12:29 AM
In response to Adding A Controller
Love the article. I dislike that the world thinks c# articles are the way to go. Love the VB, keep...

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...