我在下面写了这段代码来将主题设置为从列表中选择的值,它适用于这个页面:
protected void Page_Init(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["theme"];
Page.Theme = c == null ? "Aqua" : c.Value;
}
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["theme"];
if (!IsPostBack && (c != null))
rbList.Value = c.Value;
}
问题: 我想将相同的主题应用到所有其他页面,我在这些页面中编写了 Page_Init
函数,但是这个 Page_Init
在第二页中不起作用。我错过了什么吗??
这是我在第二页写的代码:
protected void Page_Init(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["theme"];
Page.Theme = c == null ? "Aqua" : c.Value;
}
最佳答案
检查您的 cookie 的生命周期,也许 cookie 在您设置后不久就被删除了。
我强烈建议您至少将该逻辑放在静态函数中,这样您就不会在所有页面上都有冗余代码:
PageHelper.cs
public static class PageHelper
{
public static void SetThemeFromCookie(Page page)
{
HttpCookie c = Request.Cookies["theme"];
page.Theme = c == null ? "Aqua" : c.Value;
}
}
并且在您的 Page_Init 方法中:
protected void Page_Init(object sender, EventArgs e)
{
PageHelper.SetThemeFromCookie(this);
}
关于c# - 如何在asp.net中使用Page_Init,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20521969/