Skip to content
September 11, 2011 / pauldundon

Using Images in an MVC WebGrid

The Problem: You wish to include images, or other content using HTML, in a column in a WebGrid. For example, you want to use an image for an “edit” link in each row. The HTML encoding of web grid contents makes this difficult.

Possible approach: insert placeholders where you want your images and substitute the actual HTML just before writing to the output.

Possible solution:

Add the following class to your project

Public Class WebGridFormatWrapper
    Private m_substitutions As New Dictionary(Of Guid, String)

    Public Function Format(rawFormat As Func(Of Object, String)) As Func(Of Object, String)
        Return Function(item)
                   Dim key As Guid = Guid.NewGuid
                   m_substitutions(key) = rawFormat(item)
                   Return key.ToString
               End Function
    End Function

    Public Function PostProcess(gridhtml As HtmlString) As String
        Dim result As String = gridhtml.ToString
        For Each key As Guid In m_substitutions.Keys
            result = result.Replace(key.ToString, m_substitutions(key))
        Next
        Return result
    End Function
End Class

In your view, construct an instance of the class and wrap your WebGrid format functions with calls to Format. For example, if you have a function GetImageHTML which returns an img tag, and you are using it like this:

cols.Add(grid.Column(format:=Function(currentItem) GetImageHTML(currentItem)))

Add

Dim wrapper As New WebGridFormatWrapper

and replace your code with

cols.Add(grid.Column(format:=wrapper.Format(Function(currentItem) GetImageHTML(currentItem))))

To output the grid as HTML, use

@Html.Raw(wrapper.PostProcess(grid.GetHtml(columns:=cols)))
Advertisements

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

%d bloggers like this: