[英]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
}
我嘗試將代碼復制到新類中,但是不知道如何將對代碼中下拉列表的引用鏈接到調用該函數的外部網頁。 我試過使用sender參數,例如'sender.ListThm',但它不起作用。
任何人都可以將我指向正確的方向,並避免我重復執行相同代碼的工作嗎?
您可以將發布的代碼放入用戶控件內,例如ThemeChooser.ascx
。 用戶控件將僅包含顯示可用主題的ListItem
。 使用這種方法,您只需要將用戶控件放在所需的每個頁面中,但是代碼只會存在於一個位置。
我相信您將不需要進行任何代碼更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.