ASP.NET MVC 重写RazorViewEngine实现多主题切换

    在ASP.NET
MVC中来贯彻主题的切换一般生少数栽方式,一栽是通过切换皮肤之css和js引用,一栽不畏是经还写张图引擎。通过重写视图引擎的法门更为灵敏,因为我不仅可以以不同主题下布局和体裁不相同,还可吃不同的主题下显示的数码条目不等同,就是说可以在少数主题下加加一下个性化的东西。

   
本篇我将通过重写视图引擎的章程来进展现身说法,在及时之前,我假而你都有了MVC的片基础,系统登录后是默认主题,当我们点击切换主题下,左侧菜单栏的布局变了,右侧内容的体也换了,而地址栏是休转换的。界面UI用的metronic,虽然官网是收费的,但是当天朝,总是好找到免费之。metronic是依据bootstrap的UI框架,官网地址:http://keenthemes.com/preview/metronic/

    我们事先来拘禁下效果:

   
在这边,我利用了划分区域、分模块(按独立的事体职能分)的法子,一个模块就是一个独门的dll,在这里Secom.Emx.Admin和Secom.Emx.History就是少数只独立的模块,并各自创建了区域Admin和History,当然你得于独立模块下面创建多独区域。

 

   
你晤面发现Secom.Emx.Admin模型下面的Areas目录及Secom.Emx.WebApp中的目录是同等模子一样的,其实自己最初不思量在模块项目蒙添加其它的View,但是为了便利独立布置还是加了。右键单击项目Secom.Emx.Admin,选择“属性”——“生成事件”添加如下代码:

xcopy /e/r/y $(ProjectDir)Areas\Admin\Views $(SolutionDir)Secom.Emx.WebApp\Areas\Admin\Views

   
这令很粗略,其实就算是当编译项目Secom.Emx.Admin的早晚,将项目中的Views复制到Secom.Emx.WebApp项目之指定目录下。

   
区域布局文件我停到了Secom.Emx.WebApp中,其实您了好单独放置到一个类库项目遭到,因为登记区域路由的继,项目最终会找bin目录下面有继续了AreaRegistration类的,然后为WebApp引用这类库项目,Secom.Emx.WebApp项目上加Secom.Emx.Admin、Secom.Emx.History的援。

    AdminAreaRegistration代码如下:

using System.Web.Mvc;

namespace Secom.Emx.WebApp
{
    public class AdminAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "Admin";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "Admin_default",
                "Admin/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                namespaces:new string[1] { "Secom.Emx.Admin.Areas.Admin.Controllers" }
            );
        }
    }
}

    注意命名空间和后面长的
namespaces:new string[1] {
“Secom.Emx.Admin.Areas.Admin.Controllers”
},这个命名空间就是独立模块Secom.Emx.Admin下面的控制器所于的命名空间。HistoryAreaRegistration代码如下:

using System.Web.Mvc;

namespace Secom.Emx.WebApp
{
    public class HistoryAreaRegistration : AreaRegistration 
    {
        public override string AreaName 
        {
            get 
            {
                return "History";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context) 
        {
            context.MapRoute(
                "History_default",
                "History/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                namespaces:new string[1] { "Secom.Emx.History.Areas.History.Controllers" }
            );
        }
    }
}

View Code

    我们事先押下RazorViewEngine的旧构造函数如下:

    public RazorViewEngine(IViewPageActivator viewPageActivator)  
        : base(viewPageActivator)  
    {  
        AreaViewLocationFormats = new[]  
        {  
            "~/Areas/{2}/Views/{1}/{0}.cshtml",  
            "~/Areas/{2}/Views/{1}/{0}.vbhtml",  
            "~/Areas/{2}/Views/Shared/{0}.cshtml",  
            "~/Areas/{2}/Views/Shared/{0}.vbhtml"  
        };  
        AreaMasterLocationFormats = new[]  
        {  
            "~/Areas/{2}/Views/{1}/{0}.cshtml",  
            "~/Areas/{2}/Views/{1}/{0}.vbhtml",  
            "~/Areas/{2}/Views/Shared/{0}.cshtml",  
            "~/Areas/{2}/Views/Shared/{0}.vbhtml"  
        };  
        AreaPartialViewLocationFormats = new[]  
        {  
            "~/Areas/{2}/Views/{1}/{0}.cshtml",  
            "~/Areas/{2}/Views/{1}/{0}.vbhtml",  
            "~/Areas/{2}/Views/Shared/{0}.cshtml",  
            "~/Areas/{2}/Views/Shared/{0}.vbhtml"  
        };  

        ViewLocationFormats = new[]  
        {  
            "~/Views/{1}/{0}.cshtml",  
            "~/Views/{1}/{0}.vbhtml",  
            "~/Views/Shared/{0}.cshtml",  
            "~/Views/Shared/{0}.vbhtml"  
        };  
        MasterLocationFormats = new[]  
        {  
            "~/Views/{1}/{0}.cshtml",  
            "~/Views/{1}/{0}.vbhtml",  
            "~/Views/Shared/{0}.cshtml",  
            "~/Views/Shared/{0}.vbhtml"  
        };  
        PartialViewLocationFormats = new[]  
        {  
            "~/Views/{1}/{0}.cshtml",  
            "~/Views/{1}/{0}.vbhtml",  
            "~/Views/Shared/{0}.cshtml",  
            "~/Views/Shared/{0}.vbhtml"  
        };  

        FileExtensions = new[]  
        {  
            "cshtml",  
            "vbhtml",  
        };  
    }  

View Code

   
然后新建CustomRazorViewEngine继承自RazorViewEngine,对View的路由规则进行了重写,既然可以再次写路由于规则,那表示,你得随心所欲定义规则,然后遵守自己定义的规则就是可了。需要专注的凡,要小心路由于数组中之一一,查找视图时,是以前后相继依次查找的,当找到了视图就立刻回去,不见面还去匹配后面的路由规则。为了提升路由于查找效率,我此去了独具vbhtml的路由规则,因为自尽项目被还使C#语言。

using System.Web.Mvc;

namespace Secom.Emx.WebApp.Helper
{
    public class CustomRazorViewEngine : RazorViewEngine
    {
        public CustomRazorViewEngine(string theme)
        {
            if (!string.IsNullOrEmpty(theme))
            {
                AreaViewLocationFormats = new[]
                {
                       //themes
                       "~/themes/"+theme+"/views/Areas/{2}/{1}/{0}.cshtml",
                      "~/themes/"+theme+"/Shared/{0}.cshtml"

        "~/Areas/{2}/Views/{1}/{0}.cshtml",
        "~/Areas/{2}/Views/Shared/{0}.cshtml"
    };
                AreaMasterLocationFormats = new[]
                {
                             //themes
              "~/themes/"+theme+"/views/Areas/{2}/{1}/{0}.cshtml",
              "~/themes/"+theme+"/views/Areas/{2}/Shared/{0}.cshtml",
              "~/themes/"+theme+"/views/Shared/{0}.cshtml",

        "~/Areas/{2}/Views/{1}/{0}.cshtml",
        "~/Areas/{2}/Views/Shared/{0}.cshtml"
    };
                AreaPartialViewLocationFormats = new[]
                {
                            //themes
         "~/themes/"+theme+"/views/Shared/{0}.cshtml",

        "~/Areas/{2}/Views/{1}/{0}.cshtml",
        "~/Areas/{2}/Views/Shared/{0}.cshtml"
    };

                ViewLocationFormats = new[]
                {
                            //themes
          "~/themes/"+theme+"/views/{1}/{0}.cshtml",

        "~/Views/{1}/{0}.cshtml",
        "~/Views/Shared/{0}.cshtml"
    };
                MasterLocationFormats = new[]
                {
                            //themes
         "~/themes/"+theme+"/views/Shared/{0}.cshtml",

        "~/Views/{1}/{0}.cshtml",
        "~/Views/Shared/{0}.cshtml"
    };
                PartialViewLocationFormats = new[]
                {
                            //themes
        "~/themes/"+theme+"/views/Shared/{0}.cshtml",

        "~/Views/{1}/{0}.cshtml",
        "~/Views/Shared/{0}.cshtml"
    };

                FileExtensions = new[]{"cshtml"};
            }

        }
    }
}

View Code

   
重写后,我们的路由规则以凡这样的:当没有选主题的场面下,沿用原来的路由规则,如果选择了主题,则以重复写后的路由规则。

新的路由规则:在挑了主题的状下,优先找thems/主题名称/views/Areas/区域名称/控制器名称/视图名称.cshtml,如果搜索不至还以默认的路由规则去追寻,也即是Areas/区域名称/Views/控制器名称/视图名称.cshtml。

得看到咱们摸索模板页的法吧深受改了,所以对于一些通用的,只要更换模板页就足以了,不欲丰富view界面,因为指定主题下找不交view会去默认主题下找,而view界面会引用模板页的,对于有个性化的事物,再夺指定的主题下加加新的view,不清楚自己这样表述你闹解没有,感觉较就,反正就是若可以依照卿自己之平整去寻找视图,而非是asp.net
mvc默认的规则。

 

    切换主题View代码:

                <div class="btn-group">
                    <button type="button" class="btn btn-circle btn-outline red dropdown-toggle" data-toggle="dropdown">
                        <i class="fa fa-plus"></i>&nbsp;
                        切换主题&nbsp;&nbsp;
                        <i class="fa fa-angle-down"></i>
                    </button>
                    <ul class="dropdown-menu" role="menu">
                        <li>
                            <a href="javascript:setTheme('default')">
                                <i class="icon-docs"></i> 默认主题
                            </a>
                        </li>
                        <li>
                            <a href="javascript:setTheme('Blue')">
                                <i class="icon-tag"></i> 蓝色主题
                            </a>
                        </li>
                    </ul>
                </div>
        <script type="text/javascript">
           function setTheme(themeName)
            {
               window.location.href = "/Home/SetTheme?themeName=" + themeName + "&href=" + window.location.href;
            }
        </script>

   
当用户登录成功的时光,从Cookie中读取所选取主题信息,当Cookie中尚无读取到主题记录时,则由Web.config配置文件中读取配置的主题名称,如果都不曾读取到,则证明是默认主题,沿用老的视图引擎规则。在后台管理界面,每次挑了主题,我都用主题名称存储到Cookie中,默认保存一年,这样当下次再登录的时节,就能记住所选取的主题信息了。

using System;
using System.Web.Mvc;
using Secom.Emx.WebApp.Helper;
using System.Web;
using Secom.Emx.Common.Controllers;

namespace Secom.Emx.WebApp.Controllers
{
    public class HomeController : BaseController
    {
        string themeCookieName = "Theme";
        public ActionResult Index()
        {
            ViewData["Menu"] = GetMenus();
            return View();
        }
        public ActionResult SetTheme(string themeName,string href)
        {
            if (!string.IsNullOrEmpty(themeName))
            {
                Response.Cookies.Set(new HttpCookie(themeCookieName, themeName) { Expires = DateTime.Now.AddYears(1) });
            }
            else
            {
                themeName = Request.Cookies[themeCookieName].Value ?? "".Trim();
            }
            Utils.ResetRazorViewEngine(themeName);
            return string.IsNullOrEmpty(href)? Redirect("~/Home/Index"):Redirect(href);
        }
        public ActionResult Login()
        {
            string themeName = Request.Cookies[themeCookieName].Value ?? "".Trim();
            if (!string.IsNullOrEmpty(themeName))
            {
                Utils.ResetRazorViewEngine(themeName);
            }
            return View();
        }
    }
}

    Utils类:

using System.Configuration;
using System.Web.Mvc;

namespace Secom.Emx.WebApp.Helper
{
    public class Utils
    {
        private static string _themeName;

        public static string ThemeName
        {
            get
            {
                if (!string.IsNullOrEmpty(_themeName))
                {
                    return _themeName;
                }
                //模板风格
                _themeName =string.IsNullOrEmpty(ConfigurationManager.AppSettings["Theme"])? "" : ConfigurationManager.AppSettings["Theme"];
                return _themeName;
            }
        }
        public static void ResetRazorViewEngine(string themeName)
        {
            themeName = string.IsNullOrEmpty(themeName) ? Utils.ThemeName : themeName;
            if (!string.IsNullOrEmpty(themeName))
            {
                ViewEngines.Engines.Clear();
                ViewEngines.Engines.Add(new CustomRazorViewEngine(themeName));
            }
        }
    }
}

View Code

    
实现方式实在是最为简单,简单得自己弗知晓怎么发挥才好,我或者记下来,方便有亟待之口可查阅,希望得以助到你们。由于品种引入了特大之各种有关文书以致文件较异常,网速原因无法上传源码还望见谅!