如何通过会话或cookie动态呈现样式

时间:2017-07-11 18:36:06

标签: c# asp.net-mvc session cookies

我为样式表定义了不同的包。 我尝试做这样的事情:_Layout.cshtml

@if (Session["UserId"] == null)
{
    Styles.Render("~/Content/Darkly");
}
else
{
    var User = Model.Single(x => x.UserId.ToString() == Session["UserId"].ToString());
    Styles.Render(string.Format("~/Content/{0}", User.Settings.Style));
}

但由于某种原因,这不起作用。 还有其他办法吗?

以下是BundleConfig.cs

`

        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));

        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                    "~/Scripts/modernizr-*"));

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/respond.js"));

        bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/site.css"));

        bundles.Add(new StyleBundle("~/Content/Darkly").Include(
                  "~/Content/bootstrap-darkly.css"));

        bundles.Add(new StyleBundle("~/Content/Cosmo").Include(
                  "~/Content/bootstrap-cosmo.css"));

        bundles.Add(new StyleBundle("~/Content/Lumen").Include(
                  "~/Content/bootstrap-lumen.css"));

        bundles.Add(new StyleBundle("~/Content/Cyborg").Include(
                  "~/Content/bootstrap-cyborg.css"));

        bundles.Add(new StyleBundle("~/Content/Readable").Include(
                  "~/Content/bootstrap-readable.css"));

        bundles.Add(new StyleBundle("~/Content/Cerulean").Include(
                  "~/Content/bootstrap-cerulean.css"));

`

1 个答案:

答案 0 :(得分:1)

我想我知道这里有什么问题,你应该在渲染之前添加'@'符号。

像这样:

@if (Session["UserId"] == null)
{
    @Styles.Render("~/Content/css");
}
else
{
    @Styles.Render(string.Format("~/Content/{0}", "Darkcss"));
}

这实际上会让Razor渲染Render方法的输出。