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?
The _ViewStart. cshtml page is a special view page containing the statement declaration to include the Layout page. Instead of declaring the Layout page in every view page, we can use the _ViewStart page.
Code in the _ViewStart. cshtml file will only be run for non-layout pages. Code in the _ViewImports. cshtml file will be run for both layout and non-layout pages.
It was introduced in MVC 3 along with Razor views. _Viewstart. cshtml is used to place common UI logic across the Views in the folder, where it is located. This means, the views in a single folder which is having _Viewstart.
The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.
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";
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With