Asp.net-Mvc

MVC 助手 - 使用 @URL 作為圖像 src?

  • May 18, 2012

我正在使用 MVC3 並有一個簡單的助手,它為狀態應用程序繪製一個帶有一些文本和圖示的框。一個片段:

@helper Tile(string ID)
{
<div class="front defaulttile"> 
   <div class="notifybar" id="NotifyBarID" >
   <img alt="" src="@Url.Content("~/Images/img.jpg")" style="display: inline; margin-right: 5px;" />
   <p class="topstatusbartext" id="NotifyBarTextID" >Status bar text</p>
   </div>
etc...

將 @Url.Content 用於圖像 src 會很棒,但我收到一個錯誤,它不可用。有什麼我可以添加或更改以使用它的嗎?一旦應用程序在伺服器上,我寧願不需要處理路徑並遇到問題。

謝謝!

好像有人問的比我好。看這個:

在 ASP.NET MVC 中,如何使用來自 C# 程式碼的 Razor @Url.Content() 助手?

您也可以在 MVC Helper中使用**@Href ,如下所示:**

src="@Href("../../Images/trend_up.png")" (whatever path is relative to the cshtml file)
-- or --
src="@Href("~/Images/trend_up.png")"

以上是針對 MVC3 的。

在 MVC4 中,你會得到這個不錯的快捷方式(注意 ~):

<img id="img1" src="~/Images/trend_up.png" />

感謝 Rick Anderson、Jon Galloway 和 Eilon Lipton 的幫助。

引用自:https://stackoverflow.com/questions/10645382