Conditionally display an image in webgrid

2019-08-09 08:40发布

问题:

nemesv's code Conditionally display an image in webgrid - mvc 3 works great in MVC3.

@grid.GetHtml(
  displayHeader: false,
  columns: grid.Columns(
           grid.Column(format: (item) =>
             {
               if (item.IsMainPreview == true)
             {
                return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\"/></text>", Url.Content("~/Content/images/preview-photo.gif")));
             }

In MVC4 you don't need Url.Content to use the "~". I haven't been succesful in getting the code to work without the Url.Content (it can't find the image). I have tried

return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\"/></text>", "~/Content/images/preview-photo.gif"));

and

return Html.Raw(string.Format("<text><img src={0} alt=\"Image\"/></text>", "~/Content/images/preview-photo.gif"));

among others. Does anyone know how to get this to work in MVC4 without the URL.Content?

Thank you,

回答1:

It this case it doesn't work without the Url.Content

Because the ~ replacement only works if you have it directly in your Razor template (Razor does this replacement when it parses your .cshtml and generates the response).

But the grid.GetHtml will return the rendered html which gets written into the response without any Razor parsing.

You can test it with the following code snippet (just copy into any .cshtml):

<img src="~/Content/images/preview-photo.gif" />

@{
    var img =  "<img src=\"~/Content/images/preview-photo.gif\" />";
}

@Html.Raw(img)

The first image will be displayed correctly because Razor parses it and does the ~ replacement but the second won't because the html just written as a string into the response and no parsing is involved.