Dynamic change ViewStart layout path in MVC 3

前端 未结 4 2234
囚心锁ツ
囚心锁ツ 2021-02-10 07:42

In my MVC project has 2 Areas which is Admin and Client and I need to dynamic config Layout for Client side, In _ViewStart (in client) file will set layout for all of client pag

4条回答
  •  误落风尘
    2021-02-10 08:22

    You can take advantage of Nested Layouts. Create a base controller and drive all controllers from this one.

    public class ControllerBase : Controller
    {
        public ControllerBase()
        {
            ViewBag.Theme = "~/Views/Shared/Default/Views/_Layout.cshtml";
        }
    }
    
    public class HomeController : ControllerBase
    {
        public ActionResult Index()
        {
    
            return View();
        }
    }
    

    _ViewStart.cshtml (don't make any changes in this file)

    @{
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    

    Views/Shared/_Layout.cshtml This is default Layout file of Asp.NET Mvc. Empty this and replace these lines.

    @{ 
        Layout = ViewBag.Theme;
    }
    
    @RenderBody()
    

    You can Modify this way for Areas. You can fetch active template info in BaseController from database or wherever you want.

    Btw, if you want to put your views outside of ~/Views folder search for ThemeableRazorViewEngine

提交回复
热议问题