有条件地在webgrid中显示图像 [英] Conditionally display an image in webgrid

查看:108
本文介绍了有条件地在webgrid中显示图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

nemesv的代码有条件地在webgrid中显示图像-mvc 3 在MVC3中效果很好.

  @ grid.GetHtml(displayHeader:否,列:grid.Columns(grid.Column(format:(item)=>{如果(item.IsMainPreview == true){返回Html.Raw(string.Format(< text>< img src = \" {0} \"alt =" \ Image \"/</text>",Url.Content(〜/Content/images/preview-photo.gif))));} 

在MVC4中,您不需要Url.Content即可使用〜".在没有Url.Content的情况下,代码无法成功运行(无法找到图像).我尝试过

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

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

除其他外.有谁知道如何在没有URL.Content的情况下使其在MVC4中工作?

谢谢

解决方案

在这种情况下,如果没有 Url.Content

因为替换仅在您直接将其放在Razor模板中时才有效(Razor在解析 .cshtml 并生成响应时会执行此替换).

但是 grid.GetHtml 将返回呈现的html,该html将被写入响应而无需任何Razor解析.

您可以使用以下代码段对其进行测试(只需复制到任何 .cshtml 中):

 < img src =〜/Content/images/preview-photo.gif"/>@ {var img =< img src = \"〜/Content/images/preview-photo.gif \"/>";}@ Html.Raw(img) 

第一个图像将正确显示,因为Razor会对其进行解析并进行替换,但第二个图像不会因为html只是作为字符串写入响应而没有解析./p>

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,

解决方案

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.

这篇关于有条件地在webgrid中显示图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆