Retrieving images from a dabatase in ASP.NET MVC

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 thoughts on “Retrieving images from a dabatase in ASP.NET MVC

  1. Ricardo Sánchez – Austin, TX – Ricardo Sánchez is a software engineer, meetup organizer, blogger, entrepreneur and soon-to-be self-published book author. Ricardo has worked for many companies as a software engineer building web applications and back end services. Ricardo has published various articles in software programming magazines over the years. He founded a tax preparation company in 1999 which is ran by his wife these days. In 2010 he founded a meetup group in Austin, TX to help entrepreneurs find co-founders and technical professionals to help them build their startups. This group grew from 0 to over 2,000 members in a few years and every meeting brought over 100 people. He has given talks at SXSW about networking and building meetup groups. He grew up in the city of Guadalajara, Mexico, and moved to the United States in 1995. Ricardo is in the process of writing a new book titled “The Undocumented Engineer” where he shares his immigration story. He now lives in Austin, TX with his wife and 3 children. Visit him online at www.ricardodsanchez.com
    Ricardo says:

    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.

    1. 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

    1. 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.

Leave a Reply Cancel reply