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">
        <meta charset="utf-8" />
        <script src="@"//"type="text/javascript"></script>
        <link href="@Href("~/styles/site.css")" rel="stylesheet" />
        @RenderSection("script", required: false)

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">
        tableStyle : "table",
        alternatingRowStyle : "alternate",
        headerStyle : "header"
@section script{
<script type="text/javascript">
        $('tbody tr').hover( function(){
        }).on('click', function(){
            location.href = '/Details/' + $(this).find('td:first').text();  

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

    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]);

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

A demo containing the source code is available here.