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

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

    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.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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