加入收藏 | 设为首页 | 会员中心 | 我要投稿 焦作站长网 (https://www.0391zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > Asp教程 > 正文

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

发布时间:2020-03-12 22:15:28 所属栏目:Asp教程 来源:站长网
导读:Web站点的风格切换是很常见、也很受大家欢迎的功能,比如大家熟知的博客园就提供了几十款风格模板供大家选择。

在继续进行之前,我们来考虑这样一个问题:因为我们要根据用户选择的风格来动态地为页面加载主题和模板,那么用户信息(用户选择了什么风格)应该保存在哪里,从哪里获得呢?我们有很多的选择:可以使用Session、可以使用Cookie,还可以保存到数据库中。此时最好将这部分抽象出来,以便日后为不同的方法提供实现。我们定义一个接口 IUserStyleStrategy,它用来定义如何获取、设置用户风格,在AppCode中新建文件IUserStyleStragety.cs:

public interface IUserStyleStrategy{
    void ResetUserStyle(string styleName);  // 重新设置用户风格
    string GetUserStyle();                     // 获取用户风格
}

然后我在这里提供了一个基于Cookie的默认实现:

// 默认风格设置方法:使用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); // 设置Cookie过期时间

       context.Response.Cookies.Add(cookie);

       // 因为风格(master page和theme)的动态设置只能在 PreInit 事件中
       // 而Button的Click事件在PreInit事件之后,所以需要Redirect才可以生效
       context.Response.Redirect(context.Request.Url.PathAndQuery);
    }

    // 获取用户自己设置的风格名称
    public string GetUserStyle() {     
       if (context.Request.Cookies[cookieName] != null) {
           string value = context.Request.Cookies[cookieName].Value;
           value = context.Server.UrlDecode(value);   // 避免出现中文乱码
           return value;
       } else
           return null;
    }
}

如果日后你需要将信息保存在数据库中,那么你只要重新实现一下这个接口就可以了:

// 如果将用户风格设置存储到了数据库中,可以实现这个接口
public class SqlStyleStrategy : IUserStyleStrategy {

    private int userId;          // 用户Id

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

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

    public string GetUserStyle() {
       throw new NotImplementedException();
    }
}

PageBase 类:继承自Page的基类

因为所有的页面都要运行这样的一个逻辑:判断用户是否有设置风格,如果没有,使用Web.Config中设置的默认风格;如果设置了,使用用户风格。最后动态地给Page类的Theme属性和MasterPageFile属性赋值。

(编辑:焦作站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

推荐文章
    热点阅读