How to use Relative Paths in ASP.Net

Core issue: how to make relative paths work inside a Master Page that is inherited by children at different folder levels, especially when your production site lives at a deeper folder level than your development site.

CSS Relative Paths in ASP.net -  using runat="server" in the head tag allows you to just use the ~ "web app root"  style referencing:

<head runat="server">
<title>ABC System</title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
</head>


Unfortunately this doesn't work on Javascript references, so unless you're referencing a permanent CDN you end up doing something funky inside the body tag:

<body>
<!--
This jquery script is outside head so we can use Page.ResolveURL.
For some reason:
- head: runat eq server is often required for various asp.net features
- head: runat eq server resolves "~" style CSS references, but not JS
- a code block (such as one containing Page.ResolveUrl) can't be inside a server tag.
- note I have to say "runat eq server" in this comment or the whole page parser blows up!
-->
<script src='<%=Page.ResolveUrl("~/Scripts/jquery-1.8.3.js") %>' type="text/javascript"></script>


Not great, but it works and gets you from DEV to PROD no matter your folder structure.

If there's a better way, please comment!

Comments

Popular posts from this blog

SQL 2005 SP4 and MSreplication_subscriptions

Hiding an ASPXGridView Delete button with HTMLRowCreated vs. CommandButtonInitialize

SQL Server Deadlocks - Easy Quick Start Guide