我正在学习 ASP.net,并且一直在研究主题和母版页。我决定要更改网站的主题,并使用了 web.config 解决方案(将主题添加到 web.config)。我现在想做的是能够根据用户和用户选择的主题更改主题。
我一直找不到任何教程,它们似乎都在展示如何更改单独的内容页面,但我想更改整个网站的主题。
您如何以最简单的方式做到这一点?我没有连接到数据库 atm。这只是为了练习 :)
亲切的问候
最佳答案
创建一个您继承所有页面的基页,并在 OnPreInit 事件中设置主题:
public class ThemePage : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
SetTheme();
base.OnPreInit(e);
}
private void SetTheme()
{
this.Theme = ThemeSwitcher.GetCurrentTheme();
}
}
下面是处理获取/保存当前主题和列出主题的 ThemeSwitcher 实用程序类。既然你说你没有使用数据库,你可以使用 Session:
public class ThemeSwitcher
{
private const string ThemeSessionKey = "theme";
public static string GetCurrentTheme()
{
var theme = HttpContext.Current.Session[ThemeSessionKey]
as string;
return theme ?? "Default";
}
public static void SaveCurrentTheme(string theme)
{
HttpContext.Current.Session[ThemeSessionKey]
= theme;
}
public static string[] ListThemes()
{
return (from d in Directory.GetDirectories(HttpContext.Current.Server.MapPath("~/app_themes"))
select Path.GetFileName(d)).ToArray();
}
}
您需要一个可以更改主题的页面。添加下拉列表,后面代码如下:
public partial class _Default : ThemePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
var currentTheme = ThemeSwitcher.GetCurrentTheme();
foreach (var theme in ThemeSwitcher.ListThemes())
{
var item = new ListItem(theme);
item.Selected = theme == currentTheme;
ddlThemes.Items.Add(item);
}
}
protected void ddlThemes_SelectedIndexChanged(object sender, EventArgs e)
{
ThemeSwitcher.SaveCurrentTheme(ddlThemes.SelectedItem.Value);
Response.Redirect("~/default.aspx");
}
}
您可以下载示例应用程序 here .
关于c# - 如何在运行时以编程方式更改 asp web 应用程序主题(不是页面)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019997/