【问题标题】:MVC helper - using @URL for image src?MVC 助手 - 使用 @URL 作为图像 src?
【发布时间】:2012-05-25 14:24:16
【问题描述】:

我正在使用 MVC3 并且有一个简单的助手,它可以为状态应用程序绘制一个带有一些文本和图标的框。一个sn-p:

@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 asp.net-mvc-3 html-helper


    【解决方案1】:

    看起来有人问的问题比我好。看看这个:

    In ASP.NET MVC how can I use the Razor @Url.Content() helper from C# code?

    您也可以在 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 的帮助。

    【讨论】:

      【解决方案2】:
          @helper Tile(string ID,UrlHelper url)
       {
       <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...
      

      【讨论】:

        【解决方案3】:

        在 MVC4 中,能够再次使用波浪号肯定很有趣,如答案中所述:

        src="~/Images/trend_up.png"
        

        请记住,在您的 CSS 文件中引用这些图像将无法识别 ~ - MVC4 与否。

        然而,这不是同一个问题,因为 CSS url 中对图像的相对引用。
        例如background: url('../Images/menus/menu-left.png') 将相对于 CSS 文件的位置。因此,如果您可以设法让 CSS 文件相对于其他应用程序文件夹保持不变,那么您就可以...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-09-11
          • 2016-12-05
          • 2021-11-21
          • 2016-11-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多