Reputation: 33725
When start debug mode of my asp.net website, it renders in my browser with the url
http://localhost:111/mywebsite/Default.aspx
The css file is referenced like this in the html
<link href="~/css/style.css" runat="server" rel="stylesheet" type="text/css" />
So naturally the site breaks because it looks for the CSS file in localhost:111/css/
instead of localhost:111/mywebsite/css
/.
When I launch the website, it will actually be served from the url:
http://mywebsite.com
So is there a way to reference my stylesheet properly in both my dev and production area with a simple prefix like <?=$site_url ?>
or something?
Additional info
In my solution explorer, I see that my project is marked with the path C:\...\mywebsite
. Is that why the ~
assumes my project is always in a subdirectory? How do I tell Visual Studios that this project should always be served as something like http://localhost:111/Default.aspx
?
This is what I see in the page source of both my localhost and production server:
<link href="~/css/style.css" rel="stylesheet" type="text/css"></link>
. The css is active on production, but not my localhost.
Upvotes: 0
Views: 2198
Reputation: 2136
This will do the trick.
<link href="<%=ResolveUrl("~/css/style.css")%>" runat="server" rel="stylesheet" type="text/css" />
Upvotes: 1
Reputation: 33725
I went to the solution explorer, then selected the item in the tree labelled C:\...\mywebsite
, then I went to the Properties window at bottom right of VS, and changed the Virtual path to /
. Now my dev website's root is the same as my prod website's root.
Upvotes: 1
Reputation: 10850
You already have, ~
resolves to the root of the website when the page is rendered.
Further reading: http://weblogs.asp.net/fmarguerie/archive/2004/05/05/avoiding-problems-with-relative-and-absolute-urls-in-asp-net.aspx (which works in chrome, FF and IE).
~
resolves on the server (which is why you need runat="server"
).
This code is run to generate the response from a HTTP request that has come to your dev server which is hosting the site from the location of the project on your disk.
~
doesn't assume that the site is in a subdirectory, the dev server will know the root of the website.
In production the site is being hosted by IIS from another location on the disk of the server machine.
Upvotes: 0
Reputation: 8198
Change it to:
<link href="/css/style.css"" rel="stylesheet" type="text/css" />
Remove runat="server"
(if you don't need it).
Instead of href="~/css/style.css"
use: href="/css/style.css"
href="/css/style.css"
means that there is a folder named css in root of your website and a file named style.css inside it.
UPDATE:
As pointed out by comments, this solution only works if your app is running in root.
Upvotes: -1