2012-02-27 127 views
1

我使用MVC3剃刀引擎MVC3剃刀引擎

從視圖我通話功能與Uri.Action其返回FilecontentResult

<img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" /> 

功能:

public FileContentResult GetImg(int id) 
      { 
       var byteArray = _context.Attachments.Where(x => x.Id == id).FirstOrDefault(); 
       if (byteArray != null) 
       { 
        return new FileContentResult(byteArray.Content, byteArray.Extension); 
       } 
        return null; 
      } 

如果字節組是空函數返回null

如何從視圖中知道返回的函數是什麼?

我需要的是這樣的

if(byteArray == null) 
     <img src="default img" alt="Person Image" />  
    else 
    { 
    <a class="highslide" href="@Url.Action("GetImg", "Controller", new { id = Model.Id })" id="thumb1" onclick="return hs.expand(this)"> 
         <img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" /> </a>  
     } 

回答

1
public ActionResult GetImg(int id) 
{ 
    var byteArray = _context.Attachments.Where(x => x.Id == id).FirstOrDefault(); 
    if (byteArray == null) 
    { 
     // we couldn't find a corresponding image for this id => fallback to the default 
     var defaultImage = Server.MapPath("~/images/default.png"); 
     return File(defaultImage, "image/png"); 
    } 
    return File(byteArray.Content, byteArray.Extension); 
} 

,並在你看來簡單:

<img src="@Url.Action("GetImg", "Controller", new { id = Model.Id })" alt="Person Image" /> 

,或者如果你編寫自定義HTML輔助生成該<img>標籤更簡單:

@Html.PersonImage(Model.Id) 
0

什麼是你想做的事?

如果顯示的是默認圖像,則返回默認圖像而不是null。

如果它更復雜一些(比如顯示一個上傳者或不同的鏈接),那麼在你的模型中添加一個屬性來管理它,例如,一個PersonH​​asImage布爾值。

+0

看到我的編輯職位 – Irakli 2012-02-27 11:25:58