Specify different _Layout.cshtml depending on controller

被刻印的时光 ゝ 提交于 2019-12-05 04:54:17

问题


I created an asp mvc3 project, I want to have a different _Layout.cshtml depending on which controller is selected. This is because with controller 1 it has 2 buttons with the controller2 there will be 3 and with the controller3 there will be 4. Each controller is for a specific type of user, so it depends on the login.

How can i link a controller and its views to another Layout.cshtml, right now there is one layout and it's under the Shared folder.

Thanks!


回答1:


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



回答2:


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

}


来源:https://stackoverflow.com/questions/5573881/specify-different-layout-cshtml-depending-on-controller

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