Avoid HTML Escaping in an ASP.NET MVC WebGrid Column Format

I ran into an issue with the new ASP.NET MVC WebGrid.  I had difficulty finding any information out there on a good way to do this, so I thought I would post my solution.  The WebGrid easily generates paged and sorted tables automatically. You can find more information on the ASP.NET MVC WebGrid here.  In my case, I am listing some data for the user and I want to show any new rows in bold to make it more noticeable. Adding any HTML tags to the format property as a string will result in the tags being escaped. See the following example:

@grid.GetHtml(
        columns: grid.Columns(
            grid.Column("Text", format: (item) => item.New ? item.Text : "<strong>" + item.Text + "</strong>")
        )
    )

Notice that item.New is a Boolean value.  This results in the following encoded HTML output within the table cell:

<strong>Sample Item Text</strong>

Not exactly the intended effect.  However, if you pass in a new object of type MvcHtmlString with the string in its constructor:

@grid.GetHtml(
        columns: grid.Columns(
            grid.Column("Text", format: (item) => item.New ? item.Text : new MvcHtmlString("<strong>" + item.Text + "</strong>"))
        )
    )

Voila!  This will result in the properly bolded text:

Sample Item Text

This method will work for any of the other Html Helpers as well, though my example specifically references WebGrid.  In other cases, the Html.Raw method can be used to print HTML, but inside of the grid column it will still be escaped.  I’ve tested multiple ways of adding the grid column format using “@:”, but none of the documented methods seem to work within a ternary operator.

Advertisements

One thought on “Avoid HTML Escaping in an ASP.NET MVC WebGrid Column Format

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s