How to display an image from a path in asp.net MVC

2019-01-08 18:06发布

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.

4条回答
劳资没心,怎么记你
2楼-- · 2019-01-08 18:34

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;"/>
查看更多
叼着烟拽天下
3楼-- · 2019-01-08 18:42

In your View try like this

  <img src= "@Url.Content(Model.ImagePath)" alt="Image" />
查看更多
闹够了就滚
4楼-- · 2019-01-08 18:55
 @foreach (var m in Model)
    {
      <img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
    }
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-08 18:58

you can also try with this answer :

 <img src="~/Content/img/@Html.DisplayFor(model =>model.ImagePath)" style="height:200px;width:200px;"/>
查看更多
登录 后发表回答