2017-04-23 152 views
1

我構建表單以將圖像與其他字段(如新聞標題)保存在數據庫中。當我想檢索數據庫的所有字段並查看它時,我使用的代碼是可以的,但是當圖像文件加載到數據庫時,如果圖像未加載,它將停止並且不起作用。 並非所有的消息都像這是在我的項目從數據庫檢索圖像ASP.NET MVC

<table class="table table-responsive table-bordered table-striped table-hover "> 
     <tr> 
      <th> 
       @Html.DisplayNameFor(model => model.NewsTitle) 
      </th> 

      <th> 
       @Html.DisplayNameFor(model => model.NewsImage) 
      </th> 
     </tr> 

     @foreach (var item in Model) 
     { 
      <tr> 
       <td> 
        @Html.DisplayFor(modelItem => item.NewsTitle) 
       </td> 
       <td> 
        @{ 
         var base64 = Convert.ToBase64String(item.NewsImage); 
         var imgsrc = string.Format("data:image/jpg;base64,{0}", base64); 

        } 
        <img src='@imgsrc' style="max-width:100px;max-height:100px" /> 
       </td> 

      </tr> 
         } 
    </table> 

回答

0

而且也不是所有的新聞都像這是在我的項目

我假設,如果沒有圖像是可用的,則NewsImage財產大概是null

所以,你可以這樣寫代碼:

@{ 
    var imgsrc = "url_to_your_default_image"; // useful when image is not available 
    if(item.NewsImage != null) 
    { 
     var base64 = Convert.ToBase64String(item.NewsImage); 
     imgsrc = string.Format("data:image/jpg;base64,{0}", base64); 
    } 
    <img src='@imgsrc' style="max-width:100px;max-height:100px" /> 
} 
+0

其偉大的解決問題給我 –

相關問題