Sachin Kushwaha
Sachin Kushwaha

Reputation: 33

Display image from location stored in Database asp.net mvc 3

I have complete image location stored in Database.The image is stored in that particular location. I want to display the image in the view. How to do this?

Upvotes: 1

Views: 2199

Answers (1)

Garrett Fogerlie
Garrett Fogerlie

Reputation: 4458

Since the path is not within the site you need to do this in the controller:

public ActionResult Image(int id)
{
    string imagePath = // get the image path by the id

    return File(imagePath, "image/jpg");
}

So what we have is a controller that will get the image path from the database, and return the file. Now this will return the file, but if you want to display it in the view, you would do this:

<img src="@Url.Action("Image", "ImageController", new { id = idOfImageInDB })" alt="Image Description" />

So what happens now is when the view is loading, it calls the Image action from ImageController and passes it idOfImageInDB (the database key of the image you want) and displays the image.

Note that you need to have ImageController be the name of the conctroller the Image ActionResult is in, and idOfImageInDB is the int that is used to find the image.

Upvotes: 2

Related Questions