How To Make A WebGrid Row Clickable

This snippet is one in a series showing how to use jQuery to enhance the behaviour of a Web Pages WebGrid. This example shows how to make an entire row clickable so that the user is taken to another page that displays details of the selected row.

This example makes use of the SQL CE 4.0 version of the Northwind database. It assumes that you have a layout page that references jQuery and includes a RenderSection call to an optional section named "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 page gets data from the database, specifies some columns and an AJAX update container. It also includes the jQuery that makes rows clickable in the script section:

@{
    Page.Title = "Clickable Rows";
    var db = Database.Open("Northwind");
    var query = "SELECT * FROM Customers";
    var data = db.Query(query);
    var columns = new[]{"CustomerID", "CompanyName", "ContactName", "Address", "City", "Country", "Phone"};
    var grid = new WebGrid(data, ajaxUpdateContainerId: "grid", columnNames: columns);
}
<h1>Clickable Rows</h1>
<div id="grid">
    @grid.GetHtml(    
        tableStyle : "table",
        alternatingRowStyle : "alternate",
        headerStyle : "header"
    )
</div>
@section script{
<script type="text/javascript">
    $(function(){
        $('tbody tr').live('hover', function(){
            $(this).toggleClass('clickable');
        }).live('click', function(){
            location.href = '/Details/' + $(this).find('td:first').text();  
        }); 
    });
</script>       
}

The CSS for the 'clickable' style is defined as follows:

.clickable{
    cursor: pointer;
    background: #ffff99;
}

As the user runs their cursor (hovers) over the rows of data, the current row turns yellow and the the cursor changes to a hand with a pointing finger shape. This event handler has only been applied to the table rows within the tbody element, so that the table head and foot are not affected. At the same time, the row has a click event handler added, which navigates the user to a page called Details. The text content of the first cell in each row ('td:first') is appended to the URL as UrlData. Accordingly, clicking on the first row will take the user to Details/ALFKI. The code to retrieve and display the related details in this example is simple:

@{
    Page.Title = "Details";
    var db = Database.Open("Northwind");
    var query = "SELECT * FROM Customers WHERE CustomerID = @0";
    var data = db.QuerySingle(query, UrlData[0]);

}
<h1>Details</h1>
@foreach(var item in data.GetDynamicMemberNames()){
    <strong>@item:</strong> @data[item]<br />
}

A demo containing the source code is available here.

 

Date Posted: Tuesday, August 23, 2011 11:23 AM
Last Updated: Wednesday, December 19, 2012 9:04 PM
Posted by: Mikesdotnetting
Total Views to date: 56455

7 Comments

Saturday, September 10, 2011 3:15 AM - Jacob Fernandez

Thank you for this working tutorial. But I have things in my mind. Is it reusable? What if I have 10 webgrids? What should I do with the jquery?

Tuesday, September 13, 2011 9:03 AM - Mike

@Jacob,

You can use jQuery to target specific WebGrids by placing them in their own divs, with their own id for instance.

Tuesday, October 4, 2011 3:51 PM - CodeGolem

Hi! Nice article!
Thank you for sharing.

But what if I don't want to display the ID field on the grid?

:)

Wednesday, January 18, 2012 12:49 PM - Ola

GREAT example!

The only problem for me is that after changing the grid page it stops working - the grid is not clickable any more.

Wednesday, February 15, 2012 11:34 PM - Mindaugas

Hi, your tutorials and examples are excellent. I tried to combine the jquery example from searchable webgrid with the jquery from this example but it didn't work. Both have there own <script> section but only the second one seems to be in effect. Can you point me in the right direction? Should I combine the jquery into one?

Thanks again.

@section script{

<script type="text/javascript">
$(function(){
$('th a, tfoot a').live('click', function() {
$('form').attr('action', $(this).attr('href')).submit();
return false;
});
});
</script>
}

Saturday, January 19, 2013 4:54 AM - Britto

Works Perfectly... Thx

Friday, September 5, 2014 10:28 AM - Raymond

@CodeGolem: on the ID field, add the following > .Hidden(true)
This prevents the ID from showing, but yet, you can use it since
its still there ;) (ie. if you need to redirect to a detail page or alike..)
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

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!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...