My suggestion:
Goto Global.asax
. Ensure the method Application_Start
contains following line:
protected void Application_Start()
{
...
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Find or create class BundleConfig
as follows, preferrably in folder App_Start
:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
...
bundles.Add(new StyleBundle("~page1").Include(
"~/Styles/site.css",
"~/Styles/page1.css"));
bundles.Add(new StyleBundle("~page2").Include(
"~/Styles/site.css",
"~/Styles/page2.css"));
...
bundles.Add(new StyleBundle("~pageN").Include(
"~/Styles/site.css",
"~/Styles/pageN.css"));
}
}
Now use corresponding bundle in every appropriate page:
<link rel="stylesheet" type="text/css" href="Styles/page1" />
Or better from code:
@Styles.Render("~/Styles/page1")
(this is cshtml
, but aspx
syntax is for sure very similar).
Note that you must have a separate bundle per page. You should not modify one and the same bundle on the fly. Bundles have virtual Urls. In your example it is just css
. These are cached by browsers, so regardless weather you have changed the content of bundle on the fly a browser might think this is the same and do not re-fetch it.
If you do not want to take care about adding each and every page manually to the method above. You could automate it. Following code could give you an idea how:
public class MyStyleHelper
{
public static string RenderPageSpecificStyle(string pagePath)
{
var pageName = GetPageName(pagePath);
string bundleName = EnsureBundle(pageName);
return bundleName;
}
public static string GetPageName(string pagePath)
{
string pageFileName = pagePath.Substring(pagePath.LastIndexOf('/'));
string pageNameWithoutExtension = Path.GetFileNameWithoutExtension(pageFileName);
return pageNameWithoutExtension;
}
public static string EnsureBundle(string pageName)
{
var bundleName = "~/styles/" + pageName;
var bundle = BundleTable.Bundles.GetBundleFor(bundleName);
if (bundle == null)
{
bundle = new StyleBundle(bundleName).Include(
"~/styles/site.css",
"~/styles/" + pageName + ".css");
BundleTable.Bundles.Add(bundle);
}
return bundleName;
}
}
Usage:
<link rel="stylesheet" type="text/css" href="<%: MyStyleHelper.RenderPageSpecificStyle(Page.AppRelativeVirtualPath) %>" />