zoukankan      html  css  js  c++  java
  • MVC学习系列——RazorViewEngine扩展

           有时候,我们的项目涉及到多种风格,我们可以通过扩展RazorViewEngine,这样就可以保持后台代码不发生变化。

    新建类ThemeViewEngine继承于RazorViewEngine

     1  public class ThemeViewEngine : RazorViewEngine
     2     {
     3         public ThemeViewEngine(string theme)
     4         {
     5             ViewLocationFormats = new[]
     6            {
     7                 "~/Views/Themes/" + theme + "/{1}/{0}.cshtml",
     8                 "~/Views/Themes/" + theme + "/Shared/{0}.cshtml"
     9             };
    10 
    11             PartialViewLocationFormats = new[]
    12             {
    13                 "~/Views/Themes/" + theme + "/{1}/{0}.cshtml",
    14                 "~/Views/Themes/" + theme + "/Shared/{0}.cshtml"
    15             };
    16 
    17             AreaViewLocationFormats = new[]
    18             {
    19                 "~Areas/{2}/Views/Themes/" + theme + "/{1}/{0}.cshtml",
    20                 "~Areas/{2}/Views/Themes/" + theme + "/Shared/{0}.cshtml"
    21             };
    22 
    23             AreaPartialViewLocationFormats = new[]
    24             {
    25                 "~Areas/{2}/Views/Themes/" + theme + "/{1}/{0}.cshtml",
    26                 "~Areas/{2}/Views/Themes/" + theme + "/Shared/{0}.cshtml"
    27             };
    28         }
    29     }

    Global类中,注册这种引擎

    1   //不同风格
    2             if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Theme"]))
    3             {
    4                 var activeTheme = ConfigurationManager.AppSettings["Theme"];
    5                 ViewEngines.Engines.Insert(0, new ThemeViewEngine(activeTheme));
    6             }

    web.config配置具体风格:

    1 <add key="Theme" value="China" />

    项目文件结构:

    View:

       America:

    1 @{
    2     ViewBag.Title = "ShowTheme";
    3 }
    4 
    5 <h2>ShowTheme   America</h2>

      China:

    1 @{
    2     ViewBag.Title = "ShowTheme";
    3 }
    4 
    5 <h2>ShowTheme   China</h2>

    运行:

    1  public ActionResult ShowTheme()
    2         {
    3             return View();
    4         }

    效果图:

  • 相关阅读:
    k3 cloud采购入库单单位问题
    k3 cloud没有使用协同平台开发时候的调试方式
    k3 cloud写插件不重启IIS热更新简单配置
    k3 cloud部署包中的安装包变成了浏览器,不能安装
    逻辑门
    JDBC的架构设计
    非功能性约束之性能(1)-性能银弹:缓存
    C#性能优化杂七杂八的总结
    QT QToolTip
    IDEA spotbugs使用
  • 原文地址:https://www.cnblogs.com/xuliang1992/p/5329641.html
Copyright © 2011-2022 走看看