ViewStart Introduction

In my last article series I explained that how we can generate a common page for all view which is almost similar to the concept of master page we used in asp.net.

In last article we simply created a view and add common content in it. We also add @RenderBody () method for the other content which works like content place holder in master page in asp.net.

To merge this common page to other pages we simply added Layout Property on the Top of the view and we set the path of that common layout.

Add Layout Property

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

Here _v1.cshtml is the common layout which is in shared folder. So we simply added layout property and set the path of the common view.

So in this way we came to know that if we want to merge that common page with each view then we have to add this Layout property in each view. This is the same concept we used in master page in asp.net

Advantage of ViewStart

In simple term I can say that if suppose I am adding 100 views in my project and want to add this common layout in each view then I have to set this layout property in each view.

In future if I will change this common layout name or location I have to make changes in each view too, which is little bit hectic.

So Razor View Engine introduced a new layout named _ViewStart which is applied on all view automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the other view and merges them.

In this situation we need not to set the layout property in each view.

First of all go to the view folder, right click on it and add view with name _ViewStart. Now add the layout property in _ViewStart layout.

Example of ViewStart

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

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ViewStart</title>
</head>
<body>
 
</body>
</html>

	
		

Now execute this code and see that your common layout will be merged with each view.

		
		
		ViewStart in MVC
		Figure 1
	
		

Email Address

For any query you can send mail at info@techaltum.com
Thanks