Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Nilesh LonkarRank #6,574 · 262 reputationPosted Jun 1, 2015, 11:11 PM EDT
Manoj BhoirRank #599 · 4K reputationPosted Jun 1, 2015, 10:58 PM EDT
The _ViewStart.cshtml file will execute at the start of each view's rendering. Any code contained within the code block in this file will execute before any code in the view. Typically, this file will set the layout template to be used by the views in the application:
For example, if we had_ViewStart.cshtml files in the following locations:
and we render a view in the Views\Home folder, the MVC Runtime will first execute the code in file 1 and then execute the code in file 2. Since file 3 is not in the hierarchy of the Views\Home folder, the code in file 3 will not get executed.
Reference : http://www.brainthud.com/cards/5218/19522/what-is-the-purpose-of-the-viewstartcshtml-file-and-how-is-it-used
Upendra Pratap ShahiRank #329 · 7.5K reputationPosted Jun 1, 2015, 11:28 PM EDT
Pankaj Kumar ChoudharyRank #80 · 24.4K reputationPosted Jun 2, 2015, 12:28 AM EDT
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places