Dynamic change ViewStart layout path in MVC 3

2019-03-29 23:29发布

问题:

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 page.

Layout = "~/Views/Shared/_Layout.cshtml";

So if we need to change client layout we can change Layout path of cshtml file in _ViewStart file right? I cant find how to change inside ViewStart file or Is there another solution in this case.

Thanks for your Help :)

回答1:

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?



回答2:

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



回答3:

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



回答4:

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";
}