Specify different _Layout.cshtml depending on cont

2019-03-31 09:00发布

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!

2条回答
啃猪蹄的小仙女
2楼-- · 2019-03-31 09:30

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

}
查看更多
唯我独甜
3楼-- · 2019-03-31 09:31

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";
}
查看更多
登录 后发表回答