locked
Retrieve and display images from SQL Server database in MVC view RRS feed

  • Question

  • User1677835297 posted

    I am working on an MVC application that stores images in a SQL Server 2008 database in a varbinary column.  Of course I want to retrieve them and display them in a MVC view.  Based on my internet research this has been discussed many, many times and there are lots of approaches to do this.  I store the images using Entity Framework with no problem.  As I said there are many approaches to retrieving the image and displaying it in a view.

    After trying a number of different ideas I use the following approach:

    C# Code in Controller:

    public FileContentResult GetFile(int id){          

            MediaImage mediaImage = db.MediaImage.Find(id);          

            return new FileContentResult(mediaImage.ImageData, mediaImage.ContentType);

            }

    Code in MVC view:

    @foreach (var item in Model) {

       <tr>

       <td>

       <img id = "img-size" src =  '@Url.Action("GetFile", "Media", new {id = item.MediaImageId})' alt="My Image" />

      </td>...............

    So far, it works fine, retrieves images and displays them.  Am I missing something.  Seems straight forward. 

    Any comments appreaciated.

    After posting this I found others using this same approach so I think it should be fine.  So I may have wasted your time reading this.

     

     

    Wednesday, June 13, 2012 2:19 PM

All replies

  • User1916377206 posted

    hi followed ur code but am getting an "error:Object reference not set to an instance of an object" . Could u plz rectify my error.

    My Model Class:

    using System;
        using System.Collections.Generic;
        
        public partial class Document
        {
            public int DocumentId { get; set; }
            public byte[] DocumentImageContent { get; set; }
            public Nullable<long> DocumentImageContentLength { get; set; }
            public string DocumentImageMIMEContentType { get; set; }
        }

    My Controller Class:

    public FileContentResult DisplayImagePage(int id)
            {
                Document document = db.Documents.Find(id);
                return new FileContentResult(document.DocumentImageContent, document.DocumentImageMIMEContentType);
            }

    My View:

    @model IEnumerable<DocumentImageUpload.Models.Document>

    @{
        ViewBag.Title = "DisplayImagePage";
    }

    <h2>DisplayImagePage</h2>
    <table>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    <img src =  '@Url.Action("DisplayImagePage", "Home", new { id = item.DocumentId })'/>
                </td>
            </tr>
        }
    </table>

    Tuesday, October 8, 2013 4:51 AM