ViewStart and Layout - what's the difference?

2019-04-04 00:25发布

问题:

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?

回答1:

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


回答2:

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