21

I have just started reading ASP.NET MVC 4 book and got one question. In the Razor part author said that if i dont set the Layout variable in the View.cshtml file it will as default search for a _ViewStart.cshtml, but in another part he is using _Layout.cshtml in Views/Shared, I dont get it.

If i got smth like this in View.cshtml :

@{
     Layout = null;
 }

It tells that that this View has no layout, but if i make it like :

@{

 }

So this will make that the View will search for a _ViewStart.cshtml file or _Layout.cshtml?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
CSharpBeginner
  • 1,625
  • 5
  • 22
  • 36

2 Answers2

22

Basically by default we have master layout in Views>> Shared >> _Layout.cshtml and this thing is defined in _ViewStart.cshtml that which one is our default master layout.

When we create a view with master layout by default its master layout is _Layout.cshtml, but we can change it from _ViewStart.cshtml

When we write:

@{
     Layout = null;
 }

in our view we say that this view does not have any master layout, this is used when we create partial view mostly or a standalone view without master layout.

If you open _ViewStart.cshtml by default it has this written in it:

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

and we can change it if we want to.

You can also change of some specific view Master Layout by writing on top of it the url of master layout view:

@{
        Layout = "~/Views/Shared/_CustomMasterLayout.cshtml";
 }
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Ohh gosh, nvm I noticed that he started using Layout and was like "WTF he said that empty layout will search for a ViewStart" and I have just noticed that there is also ViewStart one folder before... :D Thank you !:) – CSharpBeginner Aug 13 '14 at 15:28
1

You can set it to default (as he has done in the second example) or make your own 'custom' one (which he will probably do from now on).

The author will probably go into more/better detail once you have learnt a bit more (creating layout sheets/etc).

jbutler483
  • 24,074
  • 9
  • 92
  • 145
  • My problem is, if i leave View without setting Layout like the second snippet, then it will search for a _ViewStart.cshtml or _Layout.cshtml? ;d – CSharpBeginner Aug 13 '14 at 15:24
  • _Layout.cshtml. The ViewStart will only be used on the first page for default. Layout otherwise.(from what I recall). – jbutler483 Aug 13 '14 at 15:28
  • Nono its like Ehsan said, every View that has not setted Layout variable is searching for a _ViewStart.cshtml – CSharpBeginner Aug 13 '14 at 15:29
  • Sorry! Tbh I didn't really mess with the layout part, as there are different bootstrap 'themes' that are very useful in changing the way your website looks. But that's for another day! – jbutler483 Aug 13 '14 at 15:33