如何在asp.net MVC 4和Razor视图中显示路径中的图像?

时间:2013-04-13 10:46:30

标签: asp.net-mvc image razor

我有以下型号:

public class Player
{


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

    }

而且,这是我的.cshtml文件:

@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>

结果是简单的文字:

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

此外,我尝试了以下这一行,它的确有效:

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

如何从路径显示该图像? 根据设置,图像路径可能不同吗?还有其他想法吗?

我现在对razor语法的工作原理并不熟悉。

4 个答案:

答案 0 :(得分:117)

在你的视图中尝试这样

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

答案 1 :(得分:6)

您也可以尝试这个答案:

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

答案 2 :(得分:2)

试试这个,

<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 :(得分:1)

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