ASP.NET Web Pages - Webgrid

The webgrid in ASP.NET Web Pages is just like a standard table, but its main advantage is that it can sort columns and allows pagination. Start up Microsoft WebMatrix and create a new website based of the bakery template; name the site grid. By default the bakery site has a database with the columns ID, Name,Description, Price, and ImageName. Open the site.css file in the content folder and bottom put this code at the bottom:

table.products{width:80%;border:1px solid black;}
table.products tr td{width:5%;border:1px solid black;padding:8px;}         
table.products th{background-color:#000; color: #e6ecec; font-size: larger}
table.products th a:link{color: #FFF;}
table.products th a:visited{color: #FFF;}

This is a piece of CSS code for styling a table. Next, make a .cshtml in the root directory and name it grid. In the code blocks at the top put:

var db = Database.Open("bakery");
var sqlselect = "SELECT Name, Description, Price FROM Products";
var data = db.Query(sqlselect);

var grid = new WebGrid(source:data, rowsPerPage:5);

Code Explained

  • First we opened the database
  • We then selected the columns we want from the database
  • We then queried the database
  • Finally we made a new webgrid and set the source to data (where the webgrid data will come from) and we set how many rows there should be per page.

In the body tag put:

                tableStyle: "products",
                columns: grid.Columns(      
               grid.Column("Name","Product Name", format:@<a href="wiki/@item.Name">@item.Name</a>),
                    grid.Column("Description","Description", format: @<span style="color: #9a0606; font-weight: bold; font-style: italic;
                     grid.Column("Price","Price", format:@<text>@item.Price</text>)                                                        


We use grid.GetHtml to render the table. The tableStyle is the CSS style we want to apply. The grid.Columns specifies each column, and each column can accept a number of arguments. In this example the first string is the column name in the database, the second string is the visible name we want on the webpage and the third argument is the text we want to print out.