Specify different _Layout.cshtml depending on controller

眉间皱痕 提交于 2019-12-03 20:45:32

The View should determine the layout, not the controller.

The Controller should just determine what View is returned.

Then in the top of your view you can specify the layout. You could add a If statement around it to change it based on your data

@{
    if(ViewBag.someValue)
       Layout = "~/Views/Shared/_Layout.cshtml";
    else
        Layout = "~/Views/Shared/_otherLayout.cshtml";
}

At this point since the other one is a bit dated and with mvc 5 , I know you will have some issues with not having brackets. If you wish to use the View to be doing logic then here is a more complete answer.

Controller

public ActionResult Index()
{
    ViewBag.Admin = 1;
    return View();
}

View

@{

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!