2016-03-09 78 views
1

我試圖從本地存儲(而不是內容文件夾)中顯示圖像。我使用的圖像標籤看起來像這樣。無法在剃刀視圖中使用擴展方法

@if (Model.PreviousCoverPic != null) 
{ 
    <img src="@Url.Action("ServeImage", "Profile",new {path = Model.PreviousCoverPic})" alt="Previous Profile Pic" /> 
} 

我提出的ServerImage方法的擴展方法,因爲它會由一個以上的控制器一起使用。這裏是該方法的代碼:

public static ActionResult ServeImage(this System.Web.Mvc.Controller controller, string path) 
{ 
    Stream stream = new FileStream(path, FileMode.Open); 
    FileResult fileResult = new FileStreamResult(stream, "image/jpg"); 
    return fileResult; 
} 

它返回圖像的FileResult,以便它可以顯示。但是,渲染視圖時不顯示圖像。我檢查了Model.PreviousCoverPic值,它不爲空。我在這裏錯過了什麼?我怎樣才能實現從本地文件夾顯示方法?另外,我在this問題後面跟着回答,並添加了包含擴展方法的類的名稱空間,但該圖像仍未在視圖中呈現。

+0

您是否在cshtml中包含了定義擴展方法的命名空間? –

+0

我在Web.config文件中包含名稱空間,以便它包含在所有cshtml文件中。 – avidProgrammer

+1

我不認爲它會這樣工作。將它包含在你的cshtml中,讓我知道它是如何工作的 –

回答

2

根據以下來源

Can MVC action method be static or extension method

而這個答案

extend ASP.NET MVC action method,How to do return View

擴展方法不會與路由Url.Action工作。您可以使用繼承來創建具有該操作的基類。這樣,所有繼承的類將具有該操作並且調用Url.Action將是有效的。

public abstract class MyBaseController : Controller { 
    public ActionResult ServeImage(string path) {...} 
} 

public class ConcreteController : MyBaseController {...} 
+0

謝謝,我以這種方式工作。我認爲使用擴展方法會更清潔。有沒有辦法使用擴展方法工作? – avidProgrammer

+0

目前我想不出任何東西,還沒有遇到任何有關能夠做到這一點的文檔。 – Nkosi

+0

你說得對。操作方法不能用作擴展方法。看看[這](http://stackoverflow.com/questions/32514087/extend-asp-net-mvc-action-method-how-to-do-return-view)的問題。請修改您的答案以包含該信息。也可以返回多個內容類型,如「image/jpg」,「image/png」等。 – avidProgrammer