2011-02-15 124 views
1

如果用户没有图像,如何显示默认图像?现在,我显示如下:asp net mvc默认图像显示

<img alt="<%: Model.FullName %>" src="/Uploads/foto_<%: Model.StudentID %>.jpg" 
style="height: 125px; width: 125px" /> 

而且在某些情况下,如果我没有这个照片在上传文件夹中我没有​​得到一个形象,所以我需要一个默认的图像。

回答

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() %> 
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"; 
+0

如果您有任何疑问,随时问更多。 – lock 2011-06-26 06:31:17