开发者

Image Pathing and Absolute Paths?

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 current开发者_如何转开发ly 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.


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>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜