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="nofollow noreferrer noopener" 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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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>
Method 2
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>
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0