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

ASP.Net: How can I replace duplicated theme changing C# code to a single class?

我编写了一些代码,通过下拉列表更改页面的视觉外观,该列表在我设置的五个主题之间切换。该设置也保存在 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
  }

我试过将代码复制到一个新的 class 但不知道如何 link 将代码中对下拉列表的引用引用到调用该函数的外部网页.我尝试使用像 'sender.ListThm' 这样的发件人参数,但它不起作用。

任何人都可以指出正确的方向并避免我重复一大堆相同的代码吗?

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

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