簡體   English   中英

Visual Studio 2012條件捆綁

[英]Visual Studio 2012 Conditional Bundling

我剛開始使用VS 2012 RC。 我創建了一個包含母版頁和單個Web表單的測試站點。 目前,我正在使用此代碼捆綁網站上的整個Styles文件夾:

Global.asax中

BundleTable.Bundles.EnableDefaultBundles();

的Site.Master

<link rel="stylesheet" type="text/css" href="Styles/css" />

問題:測試站點有一個站點級CSS文件,用於控制站點的整體外觀。 除了站點級CSS之外,每個頁面都可以有自己的CSS定義。 是否可以在母版頁中僅包含site.css文件,然后在每個頁面需要時有條件地將.css文件添加到軟件包中?

我在Default.aspx后面的代碼中嘗試了這個但是它不起作用:

BundleTable.Bundles.Add(new Bundle("~/Styles/Default.css"));

我的建議:

轉到Global.asax 確保Application_Start方法包含以下行:

protected void Application_Start()
{
    ...
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

按如下方式查找或創建類BundleConfig ,最好在文件夾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"));

    }
}

現在在每個適當的頁面中使用相應的bundle:

<link rel="stylesheet" type="text/css" href="Styles/page1" />

或者更好的代碼:

@Styles.Render("~/Styles/page1")

(這是cshtml ,但aspx語法肯定非常相似)。

請注意,每頁必須有一個單獨的包。 您不應該動態修改同一個包。 捆綁包有虛擬網址。 在你的例子中它只是css 這些都是由瀏覽器緩存的,因此無論天氣如何,您都可以動態更改bundle的內容,瀏覽器可能會認為這是相同的,並且不會重新獲取它。


如果您不想將每個頁面手動添加到上述方法中。 你可以自動化它。 以下代碼可以讓您了解如何:

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;
    }
}

用法:

<link rel="stylesheet" type="text/css" href="<%: MyStyleHelper.RenderPageSpecificStyle(Page.AppRelativeVirtualPath) %>" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM