Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic change ViewStart layout path in MVC 3

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 :)

like image 573
icepon Avatar asked Dec 07 '11 17:12

icepon


People also ask

What is the difference between _viewimports Cshtml and _ViewStart Cshtml?

cshtml file. For _ViewImport. cshtml - the contents of this file applied to all the files present in the same folder and subfolder. So _ViewStart is execution whereas _ViewImport applies its content to each file.

How do I change the default layout in MVC?

The _ViewStart. cshtml can also be created in the sub-folders of the View folder to set the default layout page for all the views included in that particular subfolder. For example, the following _ViewStart. cshtml in the Home folder sets the Layout property to _myLayoutPage.

Can we have multiple _ViewStart in MVC?

We can also create multiple _ViewStart. cshtml pages. The file execution is dependent upon the location of the file within the folder hierarchy and the view being rendered. The MVC Runtime will first execute the code of the _ViewStart.


2 Answers

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?

like image 111
Brad Christie Avatar answered Nov 15 '22 12:11

Brad Christie


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

like image 33
dknaack Avatar answered Nov 15 '22 10:11

dknaack