18

In my asp.net website using MasterPage and Routing I use a tilde in the href attribute of the link tag for the stylesheet in the head section of the MasterPage. Like this:

<link href="~/Styles/Main.css" rel="stylesheet" type="text/css" />

Which works like a charm. Since the website uses routing the url will contain more and more /, yet the stylesheet's href remains valid because the tilde points to the root of the web application and the styles are used.

I tried using the same technique for the src attribute of the script tags, but this doesn't seem to produce the expected result. I tried:

<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript" ></script>

But this just outputs the tilde character to the HTML of the page instead of replacing it with the root of the web application as it does for the href attribute. My experience is that asp.net replaces tilde in href attributes but not in src attributes.

How can I make the tilde work in the src atrribute of script tags?

Bazzz
  • 26,427
  • 12
  • 52
  • 69

2 Answers2

16

I'm not sure there is a way to get it to work correctly without a bit of assistance. This should work, not as nice as the link though:

<script src="<%=ResolveUrl("~/Scripts/jquery-1.8.2.min.js")%>"></script>
armen.shimoon
  • 6,303
  • 24
  • 32
  • Haha +1 thanks for this suggestion. I think it might work but I'm inclined to mildly reject this on aesthetic grounds. I appreciate you answering my question but I was hoping for a more "elegant" solution. Asp.net already does the right behaviour for `href` attributes, I was hoping I could add `src` to a list somewhere to make it work. – Bazzz Nov 24 '12 at 09:06
  • Have you tried adding a runat="server" attribute to the script tag? – armen.shimoon Nov 24 '12 at 09:15
  • 2
    Then it attempts to execute javascript server side. Not a good plan. – Bazzz Nov 24 '12 at 10:01
  • Well, you should then add a type attribute so it knows its "text/javascript" – armen.shimoon Nov 24 '12 at 10:11
  • 1
    @armen.shimoon: ...and adding `type='text/javascript'` doesn't stop it running server-side, it tells it to run javascript server-side! – Chris Walsh Jul 29 '14 at 01:25
  • Isnt it ``? – Anders Lindén Nov 15 '20 at 20:38
1

Unfortunately, what you want just doesn't work (although I agree it should).

If you are using a script manager, then you can do something that is reasonably close:

<asp:ScriptManager>
   <Scripts>
      <asp:ScriptReference Path="~/Scripts/jquery-1.8.2.min.js" />
   </Scripts>
</asp:ScriptManager>
jmoreno
  • 12,752
  • 4
  • 60
  • 91
  • Thanks for your suggestion, but I accepted the answer a little less than 10 years ago. By now the software that uses this solution is probably end-of-life. – Bazzz Jul 13 '21 at 07:26
  • 1
    @Bazzz: I understand, I put the answer out there for others that are still dealing with this issue. – jmoreno Dec 09 '21 at 18:17