What would be best approach to link css on .aspx page in .net
In my .net application i have Styleshet.css in CSS folder.
Now i want to link this css in Sample.aspx.
What would be the best approach
1.
<link href="CSS/StyleShe开发者_开发问答et.css" rel="Stylesheet" type="text/css" />
OR
2.
<link href="<%=ConfigurationManager.AppSettings["ApplicationUrl"].ToString()%>/CSS/StyleSheet.css" rel="Stylesheet" type="text/css" />
In Web.Config
<appSettings>
<add key="ApplicationUrl" value="http://localhost/myapp/" />
</appSettings>
The best way in asp.net is option 3:
<link href="~/CSS/StyleSheet.css" rel="Stylesheet" type="text/css" />
The ~/
resolves to the site path root. The difference between this and just "css/...
is that it will work no matter what subfolder you're in. For example if your code was in
/subsection/default.aspx
and your styles were in folder /css
using a link to "css/stylesheet.css"
would resolve (incorrectly) to "/subsection/css/stylesheet.css"
whereas using "~/css/stylesheet.css"
would resolve (correctly) to "/css/stylesheet.css"
This also differs from a hard path root "/css/stylesheet.css"
in that it will work correctly regardless of the virtual directory configuration of the site.
<link href="CSS/StyleSheet.css" rel="Stylesheet" type="text/css" />
Dont go for second approach as when you deploy your site to a server the /localhost/
reference wont work.
Well, always use relative paths so that you don't have to change your files after the deployment.
You can also use resolved app relative path such as
<link href="<%= ResolveUrl("~/CSS/StyleSheet.css") %> rel="Stylesheet" type="text/css" />
Reletive path approch is much better (your first approch), Absolute paths are not portable between applications. If you move the application that the absolute path points to, the links will break.
You can find more information on below mentioned link
Specifying Paths for Resources
精彩评论