ASP.NET MVC 模版切换 自定义模板路径

不用的场景下使用不用的mvc 模版。

目录结构希望是

/templates

     Default

     Red

当传入 “Red ” 参数的时候则调用 Red 下面的View

可以直接使用默认的RazorView


   RazorView rv = new RazorView(this.ControllerContext, "~/Template/Red/Home/Index.cshtml", "~/Views/Shared/_layout.cshtml", true, new string[] { "cshtml", "vbhtml" }) ;

            return View(rv); 

 把 /Views 下面的 web.config 拷贝到 /templates 下

当然也可以自己实现一个IView

如:

namespace System.Web.Mvc
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Compilation;
    using System.Web.WebPages;

    public class ThemeRazorView : IView
    {
        private string template;
        private string layout;
        public ThemeRazorView(string _template, string _layout = "~/Views/Shared/_layout.cshtml")
        {
            template = _template;
            layout = _layout;
        }
        public void Render(ViewContext viewContext, System.IO.TextWriter writer)
        {
            if (string.IsNullOrEmpty(template))
            {
                template = "default";
            }
            string viewPath = "~/Template/" + template +"/"+ viewContext.RouteData.GetRequiredString("controller") + "/" + viewContext.RouteData.GetRequiredString("action") + ".cshtml";
            Type viewType = BuildManager.GetCompiledType(viewPath);
            WebViewPage page = Activator.CreateInstance(viewType) as WebViewPage;
            page.Layout = layout;
            page.VirtualPath = viewPath;
            page.ViewContext = viewContext;
            page.ViewData = viewContext.ViewData;
            page.InitHelpers();
            WebPageContext pageContext = new WebPageContext(viewContext.HttpContext, null, null);
            WebPageRenderingBase startPage = StartPage.GetStartPage(page, "_ViewStart", new string[] { "cshtml", "vbhtml" });
            page.ExecutePageHierarchy(pageContext, writer, startPage);
        }
    }
}



你可能感兴趣的:(mvc,String,layout,null,asp.net,action)