MVC helper - using @URL for image src?

只愿长相守 提交于 2019-12-03 01:30:47
dex3703

Looks like somebody asked the question better than me. Look at this:

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

You can also use @Href inside an MVC Helper too, like this:

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

The above are for MVC3.

In MVC4, you get this nice shortcut (notice the ~):

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

Thanks to Rick Anderson, Jon Galloway and Eilon Lipton for the help.

    @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...
DB Conner

In MVC4, it's definitely fun to be able to use the tilde again, as noted in answer:

src="~/Images/trend_up.png"

Just rememeber that references to those images in your CSS files will not recognize the ~ - MVC4 or not.

It is not the same problem however, as the relative reference to an image in CSS url.
For example background: url('../Images/menus/menu-left.png') will be relative to the location of the CSS file. So if you can manage to have the CSS file stay put relative to other application folders, you're OK...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!