Is it possible to use different layouts in MVC4 based off of routes?

Soteriologist picture Soteriologist · Aug 24, 2012 · Viewed 10.5k times · Source

I have a separate section (route) of my website that I would like to use a different layout/css etc.

So when users at the main section of my website they get the default layout. But when they log in and go to the store, the store section (route) uses a different layout/css.

So...

  • www.blahblahblah.com/
  • www.blahblahblah.com/admin/
  • www.blahblahblah.com/home/contactus/

...all use the default _Layout

BUT...

  • www.blahblahblah.com/store/
  • www.blahblahblah.com/store/admin/

...use _LayoutStore

I've seen this done based off of roles here (http://forums.asp.net/t/1653362.aspx/1) and here (How to use multiple Layout in MVC 3?) BUT I don't want to do that. I need my layout selection based off of what route the customer takes (aka view they're inside).

Thank you in advance for any and all help.

Answer

hunter picture hunter · Aug 24, 2012

Have you looked at using _ViewStart.cshtml files within any given view folder?

If that's not exactly what you're looking for and you want the values in the routing to determine which layout to use you could try creating some helper method that would return the layout to use:

    public static class LayoutHelper
    {
        public static string GetLayout(RouteData data, string defaultLayout = "")
        {
            if (data.Values["action"] == "edit")
                return "~/views/shared/_AdminLayout.cshtml";

            return defaultLayout;
        }
    }

Then you can call it from your View like so:

@{
    Layout = LayoutHelper.GetLayout(
        Request.RequestContext.RouteData,
        "~/views/shared/_layout.cshtml");
}

But it seems to me that if you created a _ViewStart.cshtml file in the Views/Store folder containing the store layout you would be good to go.