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.
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.
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.
this is good for dispalying single image we want to dispaly all the images from the table what should i write…….
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.
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
i have stored some images in binaryformat now i want to display that in a page with out using Linq how to do?
if i am using SQL SERVER then what should i write instead of “AdventureWorksEntities” ???
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.