Search code examples
c#asp.net-mvchtmlasp.net-mvc-4razor-2

how to pass an image to multiple views in MVC 4


I need to pass an image to multiple views throughout my MVC 4 project. What is the cleanest way about this? Image is saved as a byte Array. I have the image being saved to the database (this is input by the user) and I don't want to create a load of viewModels. Please note this is an MVC 4 application using Razor2 views, in C#.


Solution

  • You can go with something like this in your controller:
    For downloadable files:

    public ActionResult GetImage(string name)
    {
        byte[] image = GetImageFromDb(name);
        return File(image, "image/jpg", "image1.jpg");
    }
    

    For files included in a view/page:

    public FileContentResult GetImage(string name)
    {
        byte[] image = GetImageFromDb(name);
        return FileContentResult(image, "image/jpg");
    }
    

    And use it in your views like this:

    <img src="@Html.Action("GetImage", new { name = "image1"})">