【问题标题】:Updating dynamic css style sheet on MVC application在 MVC 应用程序上更新动态 css 样式表
【发布时间】:2020-04-27 12:55:18
【问题描述】:

我目前正在我的 MVC 应用程序上设置浅色/深色主题

它只在一个页面上工作,但是当我更改页面或刷新页面时,样式表会返回到默认页面。

HTML

<input type="button" onclick="updateStyleSheet('bootstrap-grey')" value="Dark Mode">
                <input type="button" onclick="updateStyleSheet('bootstrap')" value="Light Mode">   

JS

  <script>
        function updateStyleSheet(filename) {

            newstylesheet = "Content/" + filename + ".css";
            if ($("#dynamic_css").length == 0) {
                $("head").append("<link>")
                css = $("head").children(":last");
                css.attr({
                    id: "dynamic_css",
                    rel: "stylesheet",
                    type: "text/css",
                    href: newstylesheet
                });
            } else {
                $("#dynamic_css").attr("href", newstylesheet);
            }

        }
    </script>

捆绑配置

 public class BundleConfig
    {

        public static void RegisterBundles(BundleCollection bundles)
        {
            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"));

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

我需要更新我的 Home Controller 或我的 Bundle Config.cs 文件吗?它确实在两个样式表之间发生了变化,但是一旦它被刷新或我更改了视图,它就会回到 Bundle 配置文件中的默认值。

感谢任何帮助

【问题讨论】:

  • 您可以将值存储在会话、cookie 或用户实体中(如果他已登录)...
  • 嗨@BENARDPatrick 感谢您的回复,我如何将会话的值存储为cookie?您是否有与我的查询相关的有关如何执行此操作的任何文档或链接,我看过并找不到任何相关的。

标签: javascript c# html asp.net-mvc model-view-controller


【解决方案1】:

好的,所以您可以将此值存储为 cookie。

当您使用 c# 时

这里是关于如何在 c#https://www.ryadel.com/en/asp-net-cookie-read-write-delete-c-sharp-tutorial-guide-how-to/ 中使用 cookie 的链接

所以原理,cookie中的值存储,是一个json对象字符串化,所以你可以在里面设置更多的信息。

在服务器端

如果没有设置 cookie:

您创建了一个 cookie,其内容为:"{theme:'light'}"

如果设置了 cookie,您将不会做任何事情。

如果用户改变了主题,那么:

你解析cookie内容,修改theme的值为'dark',再次字符串化,发送给客户端。

在客户端

You check the cookie, parse it and set the custom theme...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多