似乎这不支持开箱即用,但这是我为实现主题所做的操作:
First, I Added the App_Themes folder to my project, and set up a couple of themes
然后,我决定尝试尽可能模仿 Web 表单配置文件提供程序,并向 web.config 添加配置文件属性:
<profile>
<properties>
<add name="ThemePreference" type="string" defaultValue="Blue" />
</properties>
</profile>
所以,基本上我想做的是能够在主题更改时从适当的主题文件夹加载不同的 css。我通过实现附加到 UrlHelper 类的辅助方法来做到这一点,以便我可以编写:
<link href="@Url.Theme("~/Content/Site.css")" rel="stylesheet" type="text/css" />
然后,这应该加载适当的主题 Site.css,如果没有找到文件,则返回到 ~/Content/Site.css。
这个助手非常简单:
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
SettingsProperty settingsProperty = ProfileBase.Properties["ThemePreference"];
return url.Content("~/App_Themes/"+settingsProperty.DefaultValue + u);
}
}
现在,在此版本的代码中,它只是获取默认值,因此您需要稍微调整代码。但正如您所看到的,这不仅限于 css 文件,还适用于从 .master 文件到图像的所有内容。
更新 - 使用会话而不是配置文件
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
object currentThemeName = null;
if (url.RequestContext.HttpContext.Session != null)
{
currentThemeName = url.RequestContext.HttpContext.Session["ThemePreference"];
}
return currentThemeName != null ? url.Content(String.Format("~/App_Themes/{0}{1}", currentThemeName, u)) : url.Content("~"+u);
}
}
此方法中的返回行检查是否找到 ThemePreference 会话值,然后返回所请求内容的相应 URL,否则它仅返回所请求的内容,不带 App_Theme 前缀。
在 DropDown postmethod 的控制器操作中,您只需执行以下操作:
Session.Add("ThemePreference", whateverValueYouGotFromDropdown);
更新结束
经过一些调整和修复,这应该可以解决问题。
希望它能对一些人有所帮助,尽管这不是一个完整的演练:)