2011-02-15 79 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