views:

8

answers:

2

I'm developing a website in ASP .NET MVC 2 using C#.

I have a partial view, Header.ascx. In there I have an image for my website, MainImage.png.

When I use one of the primary Views I've created, the image shows up fine. For instance, I hit the Index ActionResult of my News Controller. (site.com/News)

However, when I dig deeper, I seem to lose my image, even though the Partial view is being displayed from the Master page. i.e., if I try going to site.com/News/Article/1

Are there any suggestions for keeping my image fully intact, such as a way to do absolute pathing?

The code I currently have in my partial view is here:

<div align="center"><a href="/"><img src="../Content/images/MainImage.png" style="border:none" /></a></div>

I've tried changing the src to ~/Content/images/MainImage.png but that breaks it all over the site.

+1  A: 

Whenever possible, make the path (href or src) to resource files, like images, CSS and JS relative to the web server root. That is, your URLs should begin with a slash:

<img src="/images/imagename.png" />

That format retains the current server address (which may be an IP address, an internal network address or any of a number of public web addresses), protocol and port, and doesn't depend on the apparent path of the page the user is looking at (which can change, depending on whether the user is accessing the page by its canonical location or by a URL rewrite).

Stan Rogers
That actually got me what I need. Thanks!
Joe Morgan
A: 

Use the Url.Content helper method.

<img src="<%: Url.Content("~/content/images/imagename.png") %>" />

Same applies for when you want to include javascript files or css

<link rel="stylesheet" href="<%= Url.Content("~/content/site.css") %>" type="text/css" />
<script type="text/javascript" src="<%= Url.Content("~/content/scripts.js") %>"></script>
David Liddle