有条件地在webgrid中显示图像 - mvc 3

时间:2011-10-23 12:11:24

标签: asp.net-mvc asp.net-mvc-3 razor grid webgrid

在我的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" }))
         ));

我不确定如何在webgrid中使用if。我只是尝试过。它没有工作。忘记跟随错误

The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func<dynamic,object>, string, bool)' has some invalid arguments

1 个答案:

答案 0 :(得分:24)

grid.Column方法的format参数中,您将lambda表达式放在一起,这样您当然可以使用if。但问题是,当你在Razor中的“代码模式”输出HTML时,你不能使用@。因此,您需要将图像标记创建包装到HtmlHelper中(就像内置Html.ActionLink有很多examples)或使用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" }))
        ));

同样在最后一行而不是new { photoID = @item.Id },你应该写new { photoID = item.Id }
要了解有关剃刀的更多信息,请参阅详细tutorial