Search code examples
c#asp.net-mvcimage-rendering

Rendering image Byte data already in the view


I'm new to MVC (coming from object oriented C# exe apps) and Stackoverflow. I've been struggling with trying to run code efficiently using MVC. I have Model data that returns from the database and along with that data is a field of bytes that are a jpeg image. At this stage I've made one call to the database...

Now what I'm stuck on is that once the populated model data is in the view to be rendered, I can't simply loop over it and render the image in each data row. The only thing that I've found to make it work is to call and Action method that returns a FileContentResult, but this requires a new call back to the database for each image anew.

For solutions I've tried three different approaches that have netted the following problems:

  1. I can't seem to pass the byte array back to the controller via an Action method to satisfy how MVC wants to receive the FileContentResult back in the view. The Action method only wants to accept simple types.
  2. I obviously don't want to ask the controller to go back to the database for the byte data that I already have in the View, especially when this will involve several round trips for each entry in my Model data.
  3. Using Data Uri works, but it's not supported by enough browsers yet.

Could someone tell me what the best way to handle issues like this? Do I need to work with problem 1, or 2, or is there a different approach that I'm missing?

Here is the code I tried to use originally in problem 1 to pass the byte array back to the controller so I can render the FileContentResult:

<img src=" @{Html.RenderAction("RenderMemberImage", "Home", new { @pic = x.ThumbnailData });}" />

[HttpGet]
    public FileContentResult RenderMemberImage(byte[] pic)
    {
        return new FileContentResult(pic, "mime/jpeg");
    }

Solution

  • The problem is that you're trying to send a byte array from the browser to the server. Try something like this:

    (I haven't compiled this but it should be close)

    <img src=" @{Html.Action("RenderMemberImage", "Home", new { @picId = x.Id });}" />
    
    [HttpGet]
    public FileContentResult RenderMemberImage(Guid picId)
    {
        var pic = new Models.Picture(picId);//or however you get your data out of the DB
        return new FileContentResult(pic.ThumbnailData , "mime/jpeg");
    }
    

    Basically for each image on the page the browser will make a request to the server to get the image.