dex3703
dex3703

Reputation: 2107

MVC helper - using @URL for image src?

I'm using MVC3 and have a simple helper that draws a box with some text and icons inside for a status application. A snippet:

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

It would be great to use @Url.Content for the image src, but I get an error it's not available. Is there something I can add or change to use this? I'd rather not need to juggle paths and having a problem once the app is on the server.

Thanks!

Upvotes: 23

Views: 72081

Answers (3)

DB Conner
DB Conner

Reputation: 66

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...

Upvotes: 4

Refky Wahib
Refky Wahib

Reputation: 41

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

Upvotes: 4

dex3703
dex3703

Reputation: 2107

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.

Upvotes: 42

Related Questions