【问题标题】:Adding css while in controller在控制器中添加 css
【发布时间】:2017-04-05 00:40:57
【问题描述】:

我想将 css 名称加载到会话变量中,然后让它在 _Layout.cshtml 上加载 css。

这是我试图做的:

  var companycss = string.Format("~/Content/CompanyFiles/{0}/{0}.css", MySession.CssName);

  bundles.Add(new StyleBundle("~/Content/css").Include(
    "~/Content/bootstrap.css",
    "~/Content/site.css",
    "~/Content/justified-nav.css",
    "~/Content/Styles.css",
    companycss)); // <-- Custom CSS file

BundleConfig.cs 显然在我的 HomeController 中的 index 方法之前加载,因此它不会加载此样式表。

在我的 Index 方法中,我正在加载 MySession.CssName 并希望它能够正确加载到页面中,因为我正在决定在客户访问网站时加载哪个 css。

关于如何完成此任务的任何建议?

谢谢!

【问题讨论】:

    标签: html css asp.net-mvc twitter-bootstrap


    【解决方案1】:

    除非您为每家公司创建一个静态捆绑包,否则几乎不可能在这里实现您想要的。换句话说,您不能依赖 BundleConfig.cs 中的会话,但您可以通过会话变量在布局中引用不同的包。捆绑包必须已经定义。

    或者,如果您不介意加载两个包,您可以在视图中动态创建一个包。你基本上只是让你的~/Content/css 包包含除公司 CSS 文件之外的所有 CSS。然后你可以这样做:

    @{ BundleTable.Bundles.Add(new StyleBundle(String.Format("~/bundles/{0}", MySession.CssName)).Include(String.Format("~/Content/CompanyFiles/{0}/{0}.css", MySession.CssName))); }
    @Styles.Render(String.Format("~/bundles/{0}", MySession.CssName))
    

    这将为该特定公司的 CSS 添加一个新包,然后加载它。您最终会加载两个样式表,而不仅仅是一个,但它们都会被缩小。

    编辑

    我以前从未考虑过这一点,但您也许可以将 BundleConfig.cs 中的代码与后一个选项结合起来,实现单个捆绑包。但是,您实际上是将代码从BundleConfig.cs 转移到您的布局中。有些人可能会认为这是一个失礼,它确实践踏了 MVC 模式的原则。不过,为了完整起见:

    @{
        var companycss = string.Format("~/Content/CompanyFiles/{0}/{0}.css", MySession.CssName);
    
        BundleTable.Bundles.Add(new StyleBundle("~/Content/css").Include(
            "~/Content/bootstrap.css",
            "~/Content/site.css",
            "~/Content/justified-nav.css",
            "~/Content/Styles.css",
            companycss)); // <-- Custom CSS file
    }
    @Styles.Render("~/Content/css")
    

    【讨论】:

    • 感谢您的输入,但我会回来删除它。我走了另一条路。我将它添加到@Styles.Render("~/Content/css") 下的_layout.cshtml,这似乎有效。
    • 是的。关键是您需要在实际可用的地方使用会话变量,即 not BundleConfig.cs.
    猜你喜欢
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多