54
ASP.NET Web Pages Using The Razor Syntax
Chapter 6 – Displaying Data in a Grid
92
@grid.GetHtml(
columns: grid.Columns(
grid.Column("Name", "Product", style: "product"),
grid.Column("Description", format:@<i>@item.Description</i>),
grid.Column("Price", format:@<text>$@item.Price</text>)
)
To tell the helper which columns to display, you must include a
columns
parameter for the
GetHtml
method of the
WebGrid
helper, and pass in a collection of columns. In this collection, you
can specify each column to include. You specify an individual column to display by including a
grid.Column
object, and pass in the name of the data column you want. In this example, the
code causes the
WebGrid
object to display only three columns: Name, Description, and Price.
(These columns must be included in the SQL query results — the helper cannot display columns
that were not returned by the query.)
However, notice that in addition to just passing a column name to the
grid
, you can pass other
formatting instructions. In the example, the code displays the Name column using the following
code:
grid.Column("Name", "Product", style: "product")
This tells the
WebGrid
helper to do the following:
Display values from the Name data column.
Use the string "Product" as the column heading instead of the default name for the heading
(which in this case would be "Name").
Apply the CSS style class named "product". In the example page markup, this CSS class sets a
column width (200 pixels) and a font weight (bold).
The example for the Description column uses the following code:
grid.Column("Description", format:@<i>@item.Description</i>)
This tells the helper to display the Description column. It specifies a format by using an
expression that wraps the value from the data column in some HTML markup:
@<i>@item.Description</i>
The example for the Price column shows another variation of how to specify the
format
property:
grid.Column("Price", format:@<text>$@item.Price</text>)
This again specifies some HTML markup to render, and adds a dollar sign ($) before the column
value.
3.
View the page in a browser.