asp.net-mvc 有条件地在 webgrid 中显示图像 - mvc 3
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7866051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Conditionally display an image in webgrid - mvc 3
提问by Null Pointer
In my webgrid I need to display images based on the value .. Code is given below
在我的 webgrid 中,我需要根据值显示图像.. 代码如下
@model TraktorumMVC.Models.ManagePhotos
@{
ViewBag.Title = "ManagePhotos";
Layout = "~/Views/Shared/_Layout.cshtml";
var grid = new WebGrid(Model.AdPhotos);
}
@grid.GetHtml(
displayHeader: false,
columns: grid.Columns(
grid.Column(format: (item) =>
{
if (item.IsMainPreview == true)
{
return @<text><img src="@Url.Content("~/Content/images/preview-photo.gif")" alt="Image "/></text>;
}
else
{
return @<text><img src="@Url.Content("~/Content/images/non-preview-photo.gif")" alt="Image "/></text>;
}
}
),
grid.Column(format: (item) => Html.ActionLink("Remove Photo", "RemovePhoto", "Images", new { photoID = @item.Id }, new { @class = "RemovePhoto" }))
));
I am not sure how can i use ifin webgrid . I just tried that .Its not working .getting following error
我不确定如何if在 webgrid 中使用。我刚试过。它不工作。得到以下错误
The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func<dynamic,object>, string, bool)' has some invalid arguments
回答by nemesv
In thegrid.Columnmethod's formatparameter you are putting together a lambda expression so that you can of course use if. But the problem is you cannot use @when you are in "code mode" in Razor to output HTML. So you need to wrap the image tag creation into an HtmlHelper (like the built in Html.ActionLinkthere are lots of examples) or use the HTML.Raw method to return HTML:
在grid.Column方法的format参数中,您将一个 lambda 表达式组合在一起,以便您当然可以使用if. 但是问题是@当您在 Razor 中处于“代码模式”时无法使用来输出 HTML。所以你需要将创建的图像标签包装到一个 HtmlHelper 中(就像内置的Html.ActionLink有很多示例)或者使用 HTML.Raw 方法返回 HTML:
@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")));
}
else
{
return Html.Raw(string.Format("<text><img src=\"{0}\" alt=\"Image\"/></text>", Url.Content("~/Content/images/non-preview-photo.gif")));
}
}
),
grid.Column(format: (item) => Html.ActionLink("Remove Photo", "RemovePhoto", "Images", new { photoID = item.Id }, new { @class = "RemovePhoto" }))
));
Also in the last line instead of new { photoID = @item.Id }you should write new { photoID = item.Id }
To learn more about razor here is a detailed tutorial.
同样在最后一行而不是new { photoID = @item.Id }你应该写new { photoID = item.Id }
要了解有关剃刀的更多信息,这里有一个详细的教程。

