Using tilde in script tag src attribute

2019-02-11 21:22发布

问题:

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?

回答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>