Viewstart Page in ASP.NET MVC 3

_Viewstart Page in ASP.NET MVC 3

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

  • When a View Page Start is running, the “_ViewStart.cshtml” page will assign the Layout page for it.

  • So the application will be less maintainable.

How to create _Viewstart page

  • Add a View named _ViewStart to the project. (Remember the name “_ViewStart” is important.)

    Add a View

    Note: If it already exists, do not add any more.

    cs code

    Let’s see its effect. There is no statement to include “Layout.cshtml”.

    see its Effect

    Run the application and watch the output.

    Run the Application and watch the output

  • This is because the Layout file is included at the “_ViewStart.cshtml“ page.

    ViewStart

    Let’s comment out the code line in the _ViewStart page and run the application again and watch the output.

    Watch the Output

    Run the application.

    Run the Application

    Note: You can also explicitly add the Layout.cshtml page to the Target page.

    Layout

So the Benefit of the _ViewStart.cshtml page is:

  • Instead of declaring the Layout page individually in every page, we can include it on one place only.

  • So the application became maintainable.

  • You can still add another page as your Layout page to individual pages, regardless of your _ViewStart page.

So remove the Layout page the declaration from individual pages and put it in the “_ViewStart.cshtml” page only.

code

Watch the difference.

Watch the Difference

Run the application:

MVC Application

Up Next
    Ebook Download
    View all
    Learn
    View all