ASP.Net:如何将重复的主题更改C#代码替换为单个类?

时间:2015-08-18 19:09:09

标签: c# asp.net webforms

我写了一些代码,通过下拉列表改变了页面的视觉外观,该列表在我设置的五个主题之间交换。该设置也保存在cookie中,因此它在会话之间保持一致。这一切都可以在页面中正常工作,我可以通过将代码复制到其他页面来复制效果,但这是不好的做法,因为它在多个位置使用相同的代码。代码驻留在.cs文件后面的代码中,该代码在页面加载时运行,而另一个代码在列表更改时运行:

protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)//only runs when page first loads not on postback reload
    {
      //activeThm is the current theme for the page
      string activeThm = Page.Theme;
      //thmCook is the cookie storing the theme setting, userThm is the cookie value storing the theme the user wants
      HttpCookie thmCook = Request.Cookies.Get("userThm");//reads variable from cookie
      if (thmCook != null)
      {//test if cookie is present
        activeThm = thmCook.Value;//sets active theme to value in cookie
      }
      if (!string.IsNullOrEmpty(activeThm))
      {
        ListItem item = ListThm.Items.FindByValue(activeThm);//finds a list item that matches the active theme
        if (item != null)
        {
          item.Selected = true;//sets list to match active theme
        }
      }
    }
  }

  protected void ListThm_SelectedIndexChanged(object sender, EventArgs e)
  {
    HttpCookie thmCook = new HttpCookie("userThm");//cookie reference called thmCook created, cookie is called userThm
    thmCook.Expires = DateTime.Now.AddMonths(3);//cookie set to expire after 3 months
    thmCook.Value = ListThm.SelectedValue;
    Response.Cookies.Add(thmCook);//adds cookie
    Response.Redirect(Request.Url.ToString());//reloads current page
  }

我已尝试将代码复制到新类中,但不知道如何将代码中下拉列表的引用链接到调用该函数的外部网页。我尝试使用像'sender.ListThm'这样的sender参数,但它不起作用。

任何人都可以指出我正确的方向并保存我复制相同代码的负载吗?

1 个答案:

答案 0 :(得分:1)

您可以将发布的代码放在用户控件中,例如ThemeChooser.ascx。用户控件仅包含显示可用主题的ListItem。使用此方法,您只需将用户控件放在所需的每个页面中,但代码只存在于一个位置。

我相信您不需要进行任何代码更改。