2017-05-05 266 views
0

我正在用ASP.NET網頁創建一個網站。 我需要動態地爲html img標籤設置路徑。 我到處搜索他們已經給出了合理的答案,但他們仍然沒有爲我工作。在asp.net網頁中動態設置img標籤的src路徑Razor

映像文件的路徑 - root/Images/11.jpg

我的代碼在Upload.cshtml

@{ 
    var fileName = "11.jpg"; 
    var path = "Images/" + fileName; 

    <img src="@path" alt="image" /> 
} 

我甚至嘗試

<img [email protected] alt="image" /> 

不過它並不需要從變量的值。

回答

1

試試這個

@{ 
    string imagePath = Url.Content("~/Images/11.jpg"); 
} 

然後你img標籤可以像

<img src="@imagePath" alt="image" /> 
+0

我得到「Url不存在於當前上下文錯誤」。我也爲這個錯誤serche,但沒有得到滿意的答案。 – deelliieeD

0

我用這樣的:

@{ 
    string iSrc = "~/imagePath/11.jpg"; //The src path. 
} 

<img src='@Url.Content(iSrc)' alt="img" /> 

從@izzy以上回答應該工作以及。

+0

我得到「Url不存在於當前上下文錯誤」。我也爲這個錯誤serche,但沒有得到滿意的答案。 – deelliieeD

+0

嗯..我可能是錯的,但我認爲你可能在你的視圖中寫入剃鬚刀語法有問題。你是否能夠在你的視圖@Url中寫字。並獲得預先填充的方法列表,如操作,內容,編碼,eqauls等?如果是這種情況,請檢查此鏈接:http://stackoverflow.com/questions/27229492/error-the-name-url-does-not-exist-in-the-current-context-in-asp-net -mvc3 – Victor

0

正確的代碼 var path =「/ Images /」+ fileName;