如果用户没有图像,如何显示默认图像?现在,我这样显示:
<img alt="<%: Model.FullName %>" src="/Uploads/foto_<%: Model.StudentID %>.jpg"
style="height: 125px; width: 125px" />
在某些情况下,如果我在Uploads文件夹中没有这张照片,我就没有图片,所以我需要一张默认图片。
答案 0 :(得分:1)
在.aspx页面中使用以下代码
<asp:Image ID="Image1" runat="server" Height="125px" Width="125px" onerror="this.onload = null; this.src='profimgs/default_l.jpg';"/>
.cs页面中的使用以下
Image1.ImageUrl = "D:\profimgs\orginalimg.jpg";
答案 1 :(得分:0)
我会写一个HTML帮助器:
public static class HtmlExtensions
{
public static MvcHtmlString StudentImage(this HtmlHelper<StudentViewModel> htmlHelper)
{
var model = htmlHelper.ViewData.Model;
var relativeImagePath = "~/uploads/foto_" + model.StudentID + ".jpg";
var imagePath = htmlHelper.ViewContext.HttpContext.Server.MapPath(relativeImagePath);
var image = new TagBuilder("img");
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
image.Attributes["src"] = urlHelper.Content("~/uploads/some_generic_image.jpg");
image.Attributes["alt"] = model.FullName;
image.Attributes["style"] = "height: 125px; width: 125px";
if (File.Exists(imagePath))
{
image.Attributes["src"] = urlHelper.Content(relativeImagePath);
}
return MvcHtmlString.Create(image.ToString());
}
}
然后在您的视图中简单地说:
<%= Html.StudentImage() %>