The Beautiful Razor WebGrid
The webgrid is truly a work of art. The fastest way to show results of a query in a friendly, sortable, easily formattable fashion.
Conditionally formatting our data can sometimes offer struggles so here are a couple of tips.
Have a pesky nullable date column?
You can add something like this inside your grid - here I am working with both a status and a nullable date. So if the status equals "NA" (I set that in my query if the step wasn't relevant), I am returning a black box into the cell otherwise i am returning the sew date (item.Sew) which can be nullable - here I am returning an empty cell if null or a nicely formatted date if not.
IF STATEMENT IN GRID
,grid.Column(header:"Sew", format: (item) =>
{
if (item.SewStatus == "NA")
{
}
else
{
return item.Sew ==null ?null: item.Sew.ToString("MM/dd/yy");
}
}
)
FOREACH STATEMENT IN GRID
grid.Column(header: "NTID", canSort: true, columnName: "NTID"),
grid.Column("UserRoles", "UserRoles", format: (item) =>
{
string temp2 = string.Empty;
foreach (var rol in item.UserRoles)
{
temp2 += rol.SystemRole.RoleName + "<br />";
}
return new HtmlString(temp2);
}),
grid.Column(columnName: "firstName", header: "First Name"),
Conditionally formatting our data can sometimes offer struggles so here are a couple of tips.
Have a pesky nullable date column?
You can add something like this inside your grid - here I am working with both a status and a nullable date. So if the status equals "NA" (I set that in my query if the step wasn't relevant), I am returning a black box into the cell otherwise i am returning the sew date (item.Sew) which can be nullable - here I am returning an empty cell if null or a nicely formatted date if not.
IF STATEMENT IN GRID
,grid.Column(header:"Sew", format: (item) =>
{
if (item.SewStatus == "NA")
{
return Html.Raw(string.Format("<text><img height=40 width=100% src=\"{0}\" alt=\"Image\"/></text>", Url.Content("~/Content/images/black.png")));
}
else
{
return item.Sew ==null ?null: item.Sew.ToString("MM/dd/yy");
}
}
)
FOREACH STATEMENT IN GRID
grid.Column(header: "NTID", canSort: true, columnName: "NTID"),
grid.Column("UserRoles", "UserRoles", format: (item) =>
{
string temp2 = string.Empty;
foreach (var rol in item.UserRoles)
{
temp2 += rol.SystemRole.RoleName + "<br />";
}
return new HtmlString(temp2);
}),
grid.Column(columnName: "firstName", header: "First Name"),
Comments