How to display an image from a path in asp.net MVC 4 and Razor view?

asp.net MvcImageRazor

asp.net Mvc Problem Overview


I have the following model:

public class Player
{


    public String ImagePath
    {
        get
        {
            return "~/Content/img/sql_error.JPG";
        }

    }

And, this is my .cshtml file:

@model SoulMasters.Models.Game.Player

@{
ViewBag.Title = "Game";
Layout = "~/Views/Shared/_GameLayout.cshtml";
var imagePath = @Model.ImagePath;
}

<fieldset>
<legend>Player</legend>

   <div class="display-field">
    @Html.DisplayFor(model => model.ImagePath)
</div>
@imagePath
<div style="padding:10px;">
    
    <img src=@imagePath alt="Sample Image" width="300px" />
    
    <img  alt="asd" >
        model.ImagePath;
    </img>
</div>
</fieldset>

The result is simple text:

~/Content/img/sql_error.JPG
~/Content/img/sql_error.JPG
Sample Image asd model.ImagePath;

Also, I have tried the following line, and it works:

<img src="~/Content/img/sql_error.JPG" alt="Sample Image" width="300px" />

How to display that image from path? Could the image path be different based on settings? Any other ideas?

I don't really get it now on how razor syntax works.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

In your View try like this

  <img src= "@Url.Content(Model.ImagePath)" alt="Image" />

Solution 2 - asp.net Mvc

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>

Solution 3 - asp.net Mvc

Try this ,

<img src= "@Url.Content(Model.ImagePath)" alt="Sample Image" style="height:50px;width:100px;"/>

(or)

<img src="~/Content/img/@Url.Content(model =>model.ImagePath)" style="height:50px;width:100px;"/>

Solution 4 - asp.net Mvc

 @foreach (var m in Model)
    {
      <img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSas GabrielView Question on Stackoverflow
Solution 1 - asp.net MvcAdithyaView Answer on Stackoverflow
Solution 2 - asp.net MvcDKRView Answer on Stackoverflow
Solution 3 - asp.net MvcParameswaranView Answer on Stackoverflow
Solution 4 - asp.net MvcDebendra DashView Answer on Stackoverflow