2011-08-18 23 views
1

我有如下的控制方法,內空將圖像發送到MVC視圖中顯示如何檢查文件的結果是MVC視圖

public FileResult ShowImage(GuidID) 

{ 

DataServiceClient client = new DataServiceClient(); 

AdviserImage result; 

result = client.GetAdviserImage(ID); 


return File(result.Image, "image/jpg" ); 

} 
在我看來

我使用

<img src="<%= Url.Action("ShowImage", "Adviser", new { ID = Model.AdviserID }) %>" alt="<%:Model.LicenceNumber %>" /> 

顯示圖像

但有些ids沒有圖像並返回null,我想檢查文件的結果爲null與視圖,如果它的null不顯示圖像。

回答

0

你需要另一個是檢查數據存儲和返回ContentResult單獨的控制器動作這將是要麼truefalse(或你想告訴的ID是否有字節或沒有其他字符串),然後在視圖中,您將需要此:

if(@Html.Action("action", "controller").ToString().Equals("true", StringComparison.OrdinalIgnoreCase)){ 
// render image tag with the call to the other action that returns FileResult 
} 

另一種選擇是,你有一個視圖模型其中包含對圖像字節的引用。您準備在控制器的視圖(父模型)的模型和拉的形象出現的字節這樣的話,那麼在視圖中,您將有:

if(Model.ImageBytes.Length() > 0) { 
... do something 
} 

ImageBytes型財產爲byte[]

例如,這是我的觀點一個片段:

@model pending.Models.Section 
@if (Model != null && Model.Image != null && Model.Image.ImageBytes.Count() > 0) 
{ 
    <a href="@Model.Url" rel="@Model.Rel"> 
     <img title="@Model.Title" alt="@Model.Title" src="@Url.Action(MVC.Section.Actions.Image(Model.Id))" /></a> 
} 

HTH

+0

太棒了,非常感謝:) – 5Series

0

爲什麼不在你的控制檢查空並離開邏輯從顯示的:

result = client.GetAdviserImage(ID); 
if (result == null) 
{ 
    result = AdviserImage.Missing; 
} 

您可以創建一個默認的圖像,使之靜。如果你真的不想要顯示的圖像,然後創建一個HTML擴展方法來保持邏輯出來的觀點:

public static string AdviserImage(this HtmlHelper helper, AdviserImage image, int id, int lic) 
{ 
    if (image != null) 
    { 
     string url = string.Format("/Adviser/ShowImage/{0}", id); 
     string html = string.Format("<img src=\"{0}\" alt=\"{1}\" />", url, image.lic); 
     return html; 
    } 
    return string.Empty; // or other suitable html element 
} 
+0

您好,感謝您的答覆,但我的形象融爲一體從數據庫中讀取數據作爲咬合數據,我們可以檢查它是否爲空,並避免在視圖內完全顯示圖像標籤。 (Html.Action(「ShowImage」,「Adviser」,new {ID = Model.AdviserID})== null) – 5Series

+0

如果是這種情況,那麼HtmlHelper.Action的返回值永遠不會爲null。如果從數據庫返回的值不爲null,則需要在視圖中執行@if檢查並僅顯示標記。 –