asp.net Web站点风格切换的实现

2019-05-12 01:02:50王冬梅


       // 这里会被缓存只在第一次时调用有用
       this.styleConfig = (StyleTemplateConfiguration)ConfigurationManager.GetSection("styleTemplates");

       // 当你实现了自己的 Strategy时只需要更改这里就可以了
       // 更好的办法是将Stragey的类型保存在Web.config中,
       // 然后使用反射来动态创建
       userStrategy = new DefaultStyleStrategy("userStyle");

       // 获取用户风格
       userStyle = userStrategy.GetUserStyle();

       // 如果用户没有设置风格,使用默认风格
       if (String.IsNullOrEmpty(userStyle)) {
           userStyle = styleConfig.DefaultStyle;
           userTheme = styleConfig.DefaultTheme;
       } else {
           // 根据用户设置的风格 获取 主题名称
           userTheme = styleConfig.GetTheme(userStyle);
       }

       // 根据当前页获取MasterPage的路径
       string masterPagePath = styleConfig.GetMasterPage(userTheme);

       // 设置当前页的MasterPage
       if (masterPagePath != null)
           this.MasterPageFile = masterPagePath;

       this.Theme = userTheme;      // 设置当前页的主题
    }
}

这里需要注意:

    ConfigurationManager.GetSection()方法只会调用一次,然后会将结果进行缓存;只要Web.Config不做修改,以后不管是Request还是PostBack都不会再重新生成StyleTemplateConfig的类型实例,而会从缓存中读取。我在《.Net 自定义应用程序配置》中忘记说了。 userStrategy = new DefaultStyleStrategy("userStyle");这里可以将IUserStyleStrategy的类型信息保存在Web.config中,然后使用反射动态创建。具体方法依然参见《.Net 自定义应用程序配置》。 如果想动态地为页面设置主题和模板,代码必须写在PreInit事件中。参见《Asp.Net Page Life Cycle Overview》。

效果预览

因为这只是一个范例程序,我主要是表达实现的思路,而不是代码的编写,所以省略了很多诸如结点属性是否为空之类的判断。下面的测试仅仅在Web.Config中的配置正确时。在站点下新建一个页面,比如Default.aspx,注意创建一个模板页,因为这里设置的是会被覆盖的,所以无所谓选择哪个模板。