Web site style switching realize

Web site style switching realize

introduction

Web site style switching is very common and very popular with everyone welcome features such well-known blog park will provide dozens of style templates for your choice. In Asp.Net, we can achieve the style in the site's master page by page templates and themes theme, but the default settings provided by .Net is not strong enough and flexible. This article will tell you how to improve and expand on the .Net offers method to provide more robust website style switching function.

Effect Preview: http://www.tracefact.net/Demo/StyleSetting/default.aspx

NOTE : This article will be called master page templates (some called the master book), known as the theme topic.

Structure and templates page, theme configuration limitations

Structure of static pages

Style site switch, plainly, is actually on the page decomposition and restructuring. So Before, we briefly review the page look exactly which components may break down for us, to distinguish which is variable, which is constant, subsequent work will be much easier. Now we are temporarily out of the server, look at a static .htm page of which of these components:

Structure (with semantic XHTML) : This is a part of the marking XHTML, it should be noted that, as used herein, "semantic" as a modifier words. XHTML duty is to tell "what there is" not telling "how to display here." Although the browser for almost every XHTML tag are given some kind of built-in control style, but only the intention of XHTML specification structure of the document. For example, h1 is expressed as the title, p expressed as a paragraph. To show the word and not the larger before going to use h1.

Performance and layout (CSS): CSS to control the display and layout of the page. Before the popularity of the concept of Web standards, I think most people are tables set tables for layout, and now basically are using CSS, and here there is not much to say.

Behavior (Javascript): static pages can also add some interactive acts, these acts done by Javascript. We will often onclick = "alert ( 'hello' )" This code embedded XHTML tag, such as a mark on the Input; some configurations, the behavior of the separated mania who advocated quantitative structure (XHTML) isolated, they do not javascript code will be written between the <body>, and all written in the head, the body or below, using window.onload = function () {// ... } this form. There is a firm believer in the practice of human (Peter-Paul Koch) wrote a book called " PPK ON JavaScript ."

Well, probably this knowledge, we look at how these three separate .Net, as well as some of its limitations:

.Net separation of page structure

I still feel the behavior and structure completely separate concept too avant-garde, while it does not affect the style settings for the site, so we do not discuss it here.

We look at the structure: Now we will look to move closer to the server thinking, will soon discover that part of the structure of the above segments once again still, is the content of XHTML tags and tag (web content) separation. XHTML markup section belong content changes, different styles may require different structure of XHTML, and for each style, it shows clearly the same. Want to get this effect, we can use the Master Page template page. A Master Page template page corresponding to the XHTML structure (changes in part), corresponding to the contents of the XHTML page (constant part) by the Page page, that is, a Page can be set to a different Master Page in order to achieve a different style (look and feel).

NOTE: Here talking about CSS, if your level is strong enough CSS, XHTML code written well enough, then you do not need so complex, it can be achieved using only CSS skinning up. www.csszengarden.com have such a project to provide people around the world as a practice, which provides a unified set of XHTML code, others to write your own CSS styling to the XHTML code, the result is flourishing, exactly the same XHTML realized page design different styles.

Now look at the performance part, the presentation layer is divided into a global CSS style based on skin Skin control, which can be handed over to the theme Theme to complete.

Setting limitations on .Net

See here, you may feel not look down, use the Master Page and Theme who would not ah. Now we discuss the limitations of the Master Page and Theme under .Net:

  • As you know, we can add Theme and masterPageFile property pages node under System.Web nodes in Web.config in to set the site. But it provides a global configuration, is for all pages throughout the site, will use this Master Page. And sometimes we want to be able each page is different, there can not be realized. While we can be set separately by using the location as a node to each page, but apparently too much trouble.
  • We want each style has a name, such as "default style", "blossom."
  • We hope that users can choose the style, not like this blog Park is set by the blogger style.

Web site style switching realize

Custom style configuration

Once you have the idea we have to implement it step by step, we hope to set up a simple style, what we should first need to set clear: we have what style, what is currently used style, each style used What is the theme, which corresponds to which page template. Knowing this, we can write this node configurations:

<-! MasterPage's Path to Theme + Master + MasterRoot ->
<-! Default settings masterPage not,
     will be used when creating the page when the selected Master Page using the Default style ->
<styleTemplates default = "default style "MasterRoot =" ~ / the MasterPage ">
     <style name =" default style "Theme =" the default "> </ style>
     <style name =" blossom "Theme =" the Spring ">
          <masterpages>
               <Page path =" / Website / Default.aspx "Master =" the Default.master "/>
               <-! <Page path =" / other.aspx "Master =" the Default.master "/> ->
               <Page path =" / Default.aspx "Master =" the Default.master "/>
          </ masterpages>
     </style>
</styleTemplates>

styleTemplates is the root node style settings, default is the default style name; masterRoot refers to the address of the root directory of the template page; style nodes are each style name, and the name they use the theme; masterPages in style nodes group of nodes containing information of the template used in this style; page wherein each sub-node corresponds to a separate page, path attribute record page is the path, master page attribute is the path corresponding to each template.

master node property page does not give the full path of the template, do a directory structure in order to make more clear, there is the content master did not want to attribute becomes very long, so you need to specify the path of the template pages in the program for the masterRoot + Theme + masterPage name. Such a template in the root directory, you must create a directory with the same name as the theme, and then the template is located in the directory.

When you create a page, we need to choose a template. It is important to note that, because this template is actually the default template of the page. When we left blank in the appropriate style Web.config in the page node (no set template on this page), it will use this template. So Web.Config defined style templates, but we chose to cover this template when creating the page. As a result, we only use the definition of a complete set of Master Page template page for each page selected when created. Provided in the master page style Web.config node, it is merely cover the templates dynamically.

To the above configuration as an example: When we second page node under the "blossom" commented out, it will apply the template when creating the selected page. "Default style" did not set any of the following page node, so for each page of the style, create a template will be applied when the selected page.

If you want to use only Css to skin, you may or may not use the Master Page, you can set up such as the following in the Web.Config:

<styleTemplates default = "default style" MasterRoot = "">
     <style name = "default style" Theme = "the Default"> </ style>
     <style name = "blossom" Theme = "the Spring"> </ style>
     < style name = "autumn" Theme = "Autumn"> </ style>
</ styleTemplates>

For using the above settings Master Page, the directory structure of the site is as follows:

You can see the directory that contains the root of the Default Template page, the same as Spring and topic name (must be). After that we will write the node processing program, how to write custom nodes handler, I " .Net custom application configuration has been discussed in detail," an article, so here we look directly implemented a new in AppCode directory file StyleTemplateConfigHandler.cs:

StyleTemplateConfigHandler class public: the IConfigurationSectionHandler
{
    public the Create Object (Object parent, Object configContext, the XmlNode sectionTop) {
       return new new StyleTemplateConfiguration (sectionTop);
    }
}

// styleTemplates node mapping entity class
public class StyleTemplateConfiguration {

    Private the XmlNode Node; // junction styleTemplates point
    private string defaultTheme; // default theme name
    private string defaultStyle; // default style site name
    Private the HttpContext context;
    Private the Dictionary <String, String> styleDic; // Key: style name; Value: theme name


    public StyleTemplateConfiguration (XmlNode node ) {
       this.node = Node;
       = the HttpContext.Current context;
       styleDic new new = the Dictionary <String, String> ();

       // get all nodes style theme attribute name attribute and
       an XmlNodeList StyleList = node.SelectNodes ( "style");
       the foreach (StyleList in the XmlNode style) {
           styleDic [. style.Attributes [ "name"] the Value] = style.Attributes [ "Theme"] the Value;.
       }

       // Get the name of the site default style
       defaultStyle node.Attributes = [ "default"] the Value;.

       // The style name Get themes
       DefaultTheme = styleDic [defaultStyle];
    }

    // get all style names
    public the ICollection <String> StyleNames {
       GET {
           return styleDic.Keys;
       }
    }

    // Get the name of the subject according to the style name
    public String GetTheme (String styleName) {
       return styleDic [styleName];
    }

    // set the default style of the site get
    public String DefaultStyle {
       GET {
           return defaultStyle;
       }
       the SET {// change the Web.Config default style, typically owners can use
           the XmlDocument the XmlDocument new new DOC = ();
           doc.Load (context.Server.MapPath (@ "~ / Web.config"));
           the XmlNode = doc.DocumentElement the root;
           the XmlNode styleTemp = root.SelectSingleNode ( "styleTemplates");

           . styleTemp.Attributes [ "default"] the value = value;
           doc.Save (context.Server.MapPath (@ "~ / Web.config"));
       }
    }

    // Get the name of the default theme
    public String the DefaultTheme {
       GET DefaultTheme {return;}
    }
   
    // get the corresponding page according to the path masterPage path
    public GetMasterPage String (String userTheme) {

       // get the current page path
       string pagePath = context.Request. the path;

       the XPath for locating page // node
       string xpath = "style [@ theme = '" + userTheme + "']" + "/ masterPages / page [@ path = '" + pagePath.ToLower () + " '] ";

       // Get the path page attribute node matches
       the XmlNode pageNode = node.SelectSingleNode (XPath);

       String master;
       IF (! pageNode = null) {
           // get the master node page attribute value
           master = pageNode.Attributes [ "master"].Value;
           return prepareMasterPath(master, userTheme);
       } else
           return null;
    }
   
    // 获取 Master Page 的路径
    // MasterPagePath = 跟路径 + Theme路径 + 模板路径
    private string prepareMasterPath(string masterPath, string userTheme) {
       string path;

       if (node.Attributes["masterRoot"] != null)
           path = node.Attributes["masterRoot"].Value + "/" + userTheme + "/" + masterPath;
       else {
           if (userTheme != null) {
              path = "~/" + userTheme + "/" + masterPath;
           } else {
              path = "~/" + masterPath;
           }
       }
       return path;
    }
}

This class provides some simple operations on the XmlNode for styleTemplates node were mapped, two concepts need to be clear here: the default styles and user styles:

  • The default style refers to the style of the blogger or site administrator set up, that is, the Default property Web.Config in styleTemplates nodes.
  • User style, the style set by the user, the page is actually displayed according to user style instead of the default style. When a user does not set the style, it displays the default style.

Obviously, this type of treatment are all default style, we look at several of its main methods and properties:

// Get all the style names
public ICollection <String> GET StyleNames {{;}}

// Get the name of the theme according to the style name
public String GetTheme (String styleName) {}

// settings to get the site default style
public String DefaultStyle {}

// Gets the default theme name
public String the DefaultTheme {}
   
// Get masterPage corresponding path according to the path page
public string GetMasterPage (string userTheme) { }

IUserStyleStrategy, get, set user style

Before proceeding, let us consider the question: because we want to dynamically load the themes and templates for pages based on user-selected style, then the user information (user choose what style) should be stored where, where to get it? We have a lot of choices: You can use Session, you can use the Cookie, can also be saved to the database. At this point the best part of these abstracts it to provide for the realization of different ways. We define an interface IUserStyleStrategy, which is used to define how to obtain, set user style, AppCode create a new file in IUserStyleStragety.cs:

interface IUserStyleStrategy {public
    void ResetUserStyle (String the styleName); // reset the user style
    string GetUserStyle (); // get the user style
}

Then I am here to offer a Cookie-based default implementation:

// 默认风格设置方法:使用Cookie记录
public class DefaultStyleStrategy : IUserStyleStrategy {
   
    private string cookieName;          // cookie名称
    private HttpContext context;

    public DefaultStyleStrategy(string cookieName){
       this.cookieName = cookieName;
       context = HttpContext.Current;
    }

    // 重新设置用户风格名称
    public void ResetUserStyle(string styleName) {
       HttpCookie cookie;
       if(context.Request.Cookies[cookieName]!=null)
           cookie = context.Request.Cookies[cookieName];
       else
           cookie = new HttpCookie(cookieName);

       cookie.Value = context.Server.UrlEncode(styleName);
       cookie.Expires = DateTime.Now.AddHours (2); // set the Cookie expiration time

       context.Response.Cookies.Add (the cookie);

       // because the style (master page and theme) can only be set in PreInit dynamic events
       / / and Button's Click event after PreInit event, it is necessary to Redirect before they can take effect
       context.Response.Redirect (context.Request.Url.PathAndQuery);
    }

    // Gets the style name of the user set up their own
    public String GetUserStyle () {     
       IF ( ! context.Request.Cookies [the cookieName] = null) {
           String value = context.Request.Cookies [the cookieName] .Value;
           value = context.Server.UrlDecode (value); // Chinese garbled prevent
           return value;
       } the else
           return null;
    }
}

If in the future you will need the information stored in the database, then you just have to re-implement this interface can be a bit:

// If the user style settings are stored into the database, this interface may be implemented
public class SqlStyleStrategy: IUserStyleStrategy {
   
    Private int the userId; // User Id

    public SqlStyleStrategy (int the userId) {
       this.userId = the userId;
       // ...
    }

    public ResetUserStyle void (String the styleName) {
       the throw the NotImplementedException new new ();
    }

    public String GetUserStyle () {
       the throw the NotImplementedException new new ();
    }
}

PageBase categories: Page inherited from the base class

Because all the pages have to run such a logic: to determine whether the user has set the style, if not, use the default style set in Web.Config; if set, use the user style. Finally dynamically assigned to the Theme property of the Page class and MasterPageFile property.

Then we can set a base class to do this in the base class, and let all the pages inherit this base class; and because the page is sure to inherit from System.Web.UI.Page class, so this group class must also inherit from System.Web.UI.Page. Now in AppCode in a build file PageBase.cs:

// base class for all inherited
public class PageBase: Page
{
    protected StyleTemplateConfiguration styleConfig;
    protected String userStyle; // style set by the user
    protected string userTheme; // theme set by the user
    protected IUserStyleStrategy userStrategy; // which algorithm to use to get the user custom information
          
    protected the override void OnPreInit (EventArgs E) {
       base.OnPreInit (E);

       // this is the first time the cache is only invoked when the useful
       this.styleConfig = (StyleTemplateConfiguration) ConfigurationManager.GetSection ( " styleTemplates");

       // when you realize their Strategy only need to change it here
       // better way is to type Stragey stored in Web.config,
       // then use reflection to dynamically create
       userStrategy = new DefaultStyleStrategy ( "userStyle ");

       // Get user style
       userStyle userStrategy.GetUserStyle = ();

       // if the user does not set the style, the default style
       IF (String.IsNullOrEmpty (userStyle)) {
           userStyle = styleConfig.DefaultStyle;
           userTheme = styleConfig.DefaultTheme;
       } the else {
           / / get set by the user according to the style theme name
           userTheme = styleConfig.GetTheme (userStyle);
       }
             
       // get MasterPage path based on the current page
       String masterPagePath = styleConfig.GetMasterPage (userTheme);

       // set MasterPage current page
       if (masterPagePath =! null)
           this.MasterPageFile = masterPagePath;

       this.Theme = userTheme; // set the subject of this page
    }
}

It should be noted:

  1. ConfigurationManager.GetSection () method is only called once, and then the results will be cached; as long as Web.Config without modification, or after either Request PostBack will not re-generate the type instance StyleTemplateConfig, and reads from the cache . I " .Net custom application configuration " in forgot to say.
  2. userStrategy = new DefaultStyleStrategy ( "userStyle" ); IUserStyleStrategy herein may be the type of information stored in Web.config, and then dynamically create a reflection. Specific methods still see " .Net custom application configuration ."
  3. If you want to dynamically set the theme and template for the page, the code must be written in PreInit event. See " Asp.Net Page Life Cycle the Overview ."

Results preview

Because this is just a sample program, mainly to express my ideas implemented, instead of writing code, it omitted many such nodes to determine whether property is empty and the like. The following test only when Web.Config configuration is correct. Create a page in the site, such as Default.aspx, pay attention to create a page template as set here will be covered, so it does not matter which template to select.

Create a directory under add App_Theme Default, Spring, create a new directory MasterPage, create a directory Default, Spring below, then add some files (which I do not say it). Add on the page a DropDonwList, a Button, when we select a template to display, will make the appropriate switch, Rear write the code:

protected void Page_Load(object sender, EventArgs e) {

    if (!IsPostBack) {
       ltrStyleName.Text = userStyle;

       foreach (string styleName in styleConfig.StyleNames) {
           ListItem item = new ListItem(styleName);
           if (string.Compare(styleName, userStyle) == 0)
              item.Selected = true;
           ddlStyles.Items.Add(item);
       }
    }
}

// 更换风格
protected void Button1_Click(object sender, EventArgs e) {
    string styleName = ddlStyles.SelectedValue;
    userStrategy.ResetUserStyle(styleName); // 委托给userStragety去处理
}

Then you can see the following picture:

By following this link to see the actual results, noting: Here I let Default.aspx and Other.aspx used the same template, you can also set them to use a different template.

http://www.tracefact.net/Demo/StyleSetting/default.aspx

总结

在这篇文章中,我简单地向大家介绍了实现网站风格切换的一个思路。

我们首先复习了网页的结构,了解了.Net默认配置的不足。接着分三个步骤实现了网站的风格切换:处理配置结点的程序、获取用户风格的方法、以及通过基类继承来为各个页面设置风格。最后我们通过简单的两个页面进行了下测试和预览。

感谢阅读,希望这篇文章能给你带来帮助!

转载于:https://www.cnblogs.com/JimmyZhang/archive/2008/04/25/1170145.html

Guess you like

Origin blog.csdn.net/weixin_34115824/article/details/93444022