If you run into a ASP.NET MVC site that needs to get images stored as binary data in a SQL database you can do the following to help you read these images and display them in your view.

The Controller

First, create a controller that will serve these images and add a void method that requires the image id as parameter to locate the right image to serve. In the example below I used the Adventure Works database and Linq to query the database and read an image stored in MS SQL. Make sure you set the content type to the right type of image file you’ll be getting from the database, in the example below I used “image/gif” as the content type.

The View

In your view, you only need to use the Url.Action helper to form the url to the image stored in the database by calling the method in the image controller you just created (see above).

“Show” is the name of our method and “Image” is the name of the controller, what’s on the right to “id=” is just the image id that I want to get.

 

 

 

 

6 responses to “Retrieving images from a dabatase in ASP.NET MVC”

  1. hareesh Avatar
    hareesh

    this is good for dispalying single image we want to dispaly all the images from the table what should i write…….

    Like

  2. Ricardo Avatar

    The code above will work, you’ll just need to make some changes to the query so it pulls all images instead of one image and then in the view wrap the existing code with a loop.

    Like

    1. hareesh Avatar
      hareesh

      thanks Ricardo for replay…
      I worked as u told ,i pulled all the images with query, and in view using for
      each loop .display all the images……but it showing the error as model isnot suitable ….can u please post that code

      Like

  3. chandra kanth Avatar
    chandra kanth

    i have stored some images in binaryformat now i want to display that in a page with out using Linq how to do?

    Like

  4. tabrez Avatar
    tabrez

    if i am using SQL SERVER then what should i write instead of “AdventureWorksEntities” ???

    Like

    1. ricardodsanchez Avatar
      ricardodsanchez

      The line of code AdventureWorksEntities _data = new AdventureWorksEntities(); refers to an entity model object. By the way, I will use dependency injection (DI) these days as opposed to creating an instance of the entity model object as I did it in the example. For more details on dependency injection read this.

      Like

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I’m Ricardo

Photo of Ricardo

I enjoy coding and working with great people, as well as taking photographs, writing, reading, and traveling whenever possible.

Let’s connect

Create a website or blog at WordPress.com