Martin Boros
Martin Boros

Reputation: 798

Image file path in Razor .cshtml view file

In the website I'm creating, I'm trying to store a URL to an uploaded image into my model and calling to it in the view. So when I type out the file path in the source for the HTML, it works fine.

<dd><img src="~/uploads/image.jpg" alt="ASP.NET" style="width:350px;height:260px" />
    </dd>

But if I try to call from the model, the URL gets messed up.

@string imagePath = "~/uploads/" + Model.Picture;

 <dd><img src=@imagePath alt="ASP.NET" style="width:350px;height:260px" />
    </dd>

That code links to "http://localhost:60847/Controller/Details/~/uploads/image.jpg" . Could someone explain to me why it's working differently? Thank you.

Upvotes: 1

Views: 10649

Answers (1)

Shyju
Shyju

Reputation: 218892

You are missing quotes around the src property value. Also make sure you use the Url.Content helper method to get the correct path. You may pass "~" to this method to get the correct path to your app root.

@{ string imagePath = Url.Content("~/uploads/" + Model.Picture); };
<img src="@imagePath" alt="ASP.NET" style="width:350px;height:260px" />

Or even a single liner without the variable

<img src="@Url.Content("~/uploads/" + Model.Picture)"  />

Upvotes: 4

Related Questions