myasp.net MVC Web应用程序中有以下代码:
<a href="~/Content/uploads/@(item.ID).png"><img class="thumbnailimag" src="~/Content/uploads/@(item.ID).png" /></a> @Html.ActionLink(item.Name,"Details","DataCenter",new{id = item.ID},null)
和以下CSS:
.thumbnailimag { width:30px; height:30px; border:thin blue; background-image:url("/Content/uploads/virtual-data-center.jpg"); }
但是,如果图像不存在,每个保镖将对待它不同.我设置了一个背景图像,但仍然在IE上将在默认图像上显示“X”,如下所示:
如果src不存在,有没有办法显示默认图像?
解决方法
处理这个服务器端的情况要好得多:
public static class HtmlHelperExtensions { public static string ImageOrDefault(this HtmlHelper helper,string filename) { var imagePath = uploadsDirectory + filename + ".png"; var imageSrc = File.Exists(HttpContext.Current.Server.MapPath(imagePath)) ? imagePath : defaultImage; return imageSrc; } private static string defaultImage = "/Content/DefaultImage.png"; private static string uploadsDirectory = "/Content/uploads/"; }
那么你的看法被简化为:
<img src="@Html.ImageOrDefault(item.ID)" />