Dynamic change ViewStart layout path in MVC 3

前端 未结 4 2235
囚心锁ツ
囚心锁ツ 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:15

    Remember that anything within the @{ ... } is treated as code. So, it should be a simple matter of placing a condition in there to change how it's inherited:

    @{
      Layout = "~/Views/Shared/_Layout.cshtml";
      if (User.Current.IsAuthenticated) {
        Layout = "~/Views/Shared/_AdminLayout.cshtml";
      }
    }
    

    Though you're probaby better off looking at Themes (and have an admin/user theme). Alternatively, you can make your _Layout.cshtml smarter and have it handle the different views based on conditions as well.

    See Also: MVC3 Razor - Is there a way to change the Layout depending on browser request?

    0 讨论(0)
  • 2021-02-10 08:18

    Your question has not enough information to give you a complete code sample.

    But basicly you can do this

    if (InsertIsAdminLogicHere) {
         Layout = "~/Views/Shared/_AdminLayout.cshtml";
    } else {
         Layout = "~/Views/Shared/_Layout.cshtml";
    }
    

    If you show us how you determine admin or not, we can provide more help.

    hope this helps

    0 讨论(0)
  • 2021-02-10 08:18

    in Views/_ViewStart.cshtml

    @{    
    object multiTenant;
    if (!Request.GetOwinContext().Environment.TryGetValue("MultiTenant", out multiTenant))
    {
        throw new ApplicationException("Could not find tenant");
    }
    Layout = "~/Views/"+ ((Tenant)multiTenant).Name + "/Shared/_Layout.cshtml";
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题