Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify different _Layout.cshtml depending on controller

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!

like image 788
bb2 Avatar asked Dec 06 '25 16:12

bb2


2 Answers

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";
}
like image 51
Daveo Avatar answered Dec 08 '25 06:12

Daveo


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

}
like image 29
Tom Stickel Avatar answered Dec 08 '25 08:12

Tom Stickel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!