Tuesday, July 5, 2011

ASP.NET Razor - The WebGrid Helper



WebGrid - One of many useful Web Helpers.

Doing the HTML Yourself

In the previous chapter, you displayed database data by using razor code, and doing all the HTML markup yourself:

Razor Example

@{
var db = Database.Open("SmallBakery");
var selectQueryString = "SELECT * FROM Product ORDER BY Name";
}

<html>
<body>
<h1>Small Bakery Products</h1>
<table>
<tr>
<th>Id</th>
<th>Product</th>
<th>Description</th>
<th>Price</th>
</tr>
@foreach(var row in db.Query(selectQueryString))
{

<tr>
<td>@row.Id</td>
<td>@row.Name</td>
<td>@row.Description</td>
<td aligh="right">@row.Price</td>
</tr>
}
</table>
</body>
</html>

Using The WebGrid Helper

Using the WebGrid helper is an easier way to display data.
The WebGrid helper:
  • Automatically sets up an HTML table to display data
  • Supports different options for formatting
  • Supports paging through data
  • Supports Sorting by clicking on column headings

Razor WebGrid Example

@{
var db = Database.Open("SmallBakery") ;
var selectQueryString = "SELECT * FROM Product ORDER BY Id";
var data = db.Query(selectQueryString);
var grid = new WebGrid(data);
}

<html>
<head>
<title>Displaying Data Using the WebGrid Helper</title>
</head>
<body>
<h1>Small Bakery Products</h1>
<div id="grid">
@grid.GetHtml()
</div>
</body>
</html>

No comments:

Post a Comment