Abrar Ahmad
Abrar Ahmad

Reputation: 100

Image tag is not showing image while image url is fine. MVC

I am new to asp.net MVC. I have the image source in database with the following:

@Model.Image2Url = "C:\Users\vasamad\Documents\VisualStudio2015\Projects\ReactMVC\ReactMVC\Content\Images\Products\3.jpg"

I am adding it to view like this

<img src="@Model.Image2Url" alt="No Image"/>

in browser inspect Element "Could Not load the image" when I copy this URL and past in new tab its showing the image.

Upvotes: 0

Views: 483

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039598

You should store a relative image path to your MVC application root:

~/Content/Images/Products/3.jpg

If you want full image paths then you will need to write a controller action that will read this image from the absolute path and stream it to the response. Finally the <img> tag will need to point to this new controller action. Here's an example:

public ActionResult MyImage()
{
    // Get this from your database
    string absoluteImagePath = "C:\\Users\\vasamad\\Documents\\VisualStudio2015\\Projects\\ReactMVC\\ReactMVC\\Content\\Images\\Products\\3.jpg";
    return File(absoluteImagePath, "image/jpeg");
}

and then in your view point the image tag to this action:

<img src="@Url.Action("MyImage", "MyController")" alt="" />

Upvotes: 1

Related Questions