Reputation: 877
I am trying to display images from the local storage(not Content folder). The image tag I am using looks like this.
@if (Model.PreviousCoverPic != null)
{
<img src="@Url.Action("ServeImage", "Profile",new {path = Model.PreviousCoverPic})" alt="Previous Profile Pic" />
}
I made the ServerImage method an extension method since it will be used by more than one controller. Here is the code for the method:
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;
}
It returns a FileResult of the image so that it can be displayed. However, when the view is rendered it doesn't show the image. I checked the Model.PreviousCoverPic value and it is not null. What am I missing here? How can I achieve displaying methods from a local folder? Also, I followed the answer in this question and added the name space of the class which contains the extension method but the image still doesn't get rendered in the view.
Upvotes: 1
Views: 1818
Reputation: 247551
According to the following sources
Can MVC action method be static or extension method
And this answer
extend ASP.NET MVC action method,How to do return View
The extension method wont work with routing the Url.Action
. You can use inheritance to make a base class with the action. that way all inherited classes will have the action and calls to Url.Action
will be valid.
public abstract class MyBaseController : Controller {
public ActionResult ServeImage(string path) {...}
}
public class ConcreteController : MyBaseController {...}
Upvotes: 2