我想在我的网站上添加使用完全不同视图的主题。我希望在我的项目中看到它们:
Views/Theme1/...
Views/Theme2/...
而不是默认
Views/...
因为我需要一种简单的方法来切换它们。
所以问题是:如何让ViewEngine在所提到的特定位置查找视图,例如在web.config中?
加
用Archil解决了这个基本问题:
public class ThemedRazorViewEngine : RazorViewEngine
{
public ThemedRazorViewEngine(string themeName)
{
MasterLocationFormats = new string[] { "~/Views/" + themeName + "/Shared/{0}.cshtml" };
PartialViewLocationFormats = new string[] { "~/Views/" + themeName + "/{1}/{0}.cshtml" };
ViewLocationFormats = new string[] { "~/Views/" + themeName + "/{1}/{0}.cshtml" };
}
}
一切都很好,但“右键点击 - >转到查看”不再起作用(副作用,没什么大不了的。)
现在我提出了另一个问题:在网站上我们有管理面板,应该是主题独立的。我该如何解决这个问题?有类似的东西:
Views/Admin/...
Views/Theme1/...
Views/Theme2/...
答案 0 :(得分:2)
如何让ViewEngine在特定位置查找视图 提及。
您需要在View方法中提供路径:
return View("~/Views/Theme1/Index");
return View("~/Views/Theme2/Index");
对于web.config
示例:
var themeFromWebConfig = GetThemeFromWebConfig();
var viewName = "~/Views/" + themeFromWebConfig + "/Index";
return View(viewName);
答案 1 :(得分:2)
web.config中最简单的主题值解决方案是创建自定义ViewEngine并仅覆盖视图搜索位置。这样你就不必在Controller中改变任何东西(例子只使用c#only视图引擎的cshtml文件,如果你想使用visual basic视图,你必须添加vbhtml扩展名)
public class ThemedRazorViewEngine : RazorViewEngine
{
public ThemedRazorViewEngine(string themeName)
{
AreaMasterLocationFormats = new string[] { "~/Areas/{2}/Views/ " + themeName + "/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/" + themeName + "/{0}.cshtml" };
//and same for all of below
AreaPartialViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" };
AreaViewLocationFormats = new string[] { "~/Areas/{2}/Views/{1}/{0}.cshtml", "~/Areas/{2}/Views/Shared/{0}.cshtml" };
FileExtensions = new string[] { "cshtml" };
MasterLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
PartialViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
ViewLocationFormats = new string[] { "~/Views/{1}/{0}.cshtml", "~/Views/Shared/{0}.cshtml" };
}
}
注册视图引擎
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new ThemedRazorViewEngine(ConfigurationManager.AppSettings["currentTheme"]));