2013-04-13 68 views
44

我有以下型號:如何在asp.net MVC 4和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 [email protected] 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" /> 

如何從路徑顯示該圖像? 根據設置,圖像路徑可能會有所不同嗎?任何其他想法?

我現在還不知道如何使用剃刀語法。

+1

試試這個'' –

回答

101

在您查看嘗試這樣

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

按預期工作,謝謝:) –

+0

@SasGabriel不客氣:) – Adithya

+0

嗨,我將數據庫中的Imagepath保存爲:'c:// user/tom/images',我無法在視圖中檢索它爲什麼? – stom

6

你也可以用這個答案嘗試:

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

請不要發佈代碼轉儲,而是解釋爲什麼此代碼可以解決問題。 – Rakete1111

1

試試這個,

<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;"/> 
相關問題