Create an ASP.NET Core Application Part III

This post is part of a series

There is an important folder within the “Pages” folder called “Shared” that contains partials. This is where you would, for example, have the layout page that defines the structure of the site. In the image below, you can see the “_Layout.cshtml” page. This is often one of the most important pages on your site.

This page contains the markup and that defines the structure of your site. In the old days, we might call these the master pages. Often they will include a header and a footer and navigation elements. Then in the middle, they will contain the body — using the @RenederBody() method — which In a Razor layout page renders the portion of a content page that is not within a named section.

In concept, it may look like the following…

Page Layout example

In HTML code, it looks more like this…

Running Code Before Each View

Any code that needs to run before each view or page should be placed in the _ViewStart.cshtml file. The statements listed in _ViewStart.cshtml are run before every full view.

A sample _ViewStart.cshtml file:

The file above specifies that all views will use the _Layout.cshtml layout.

In a non-partial page, you define the contents of the page

  • Include the @page directive
  • Reference the @model. This simply means adding a reference to the class that has the code-behind. In the example below, we are referencing the IndexModel, since the name of the page is Index.cshtml, and the class that contains the code-behind is called IndexModel
  • Add any additional data you want to show. For instance we can set the title of the page (in the example below using ViewData)
  • Finally, add the body of the page. You do not need to include html, body, header or footer elements — as these are taken care of in the _Layout. In the example below, the body begins with the <div> element.

The above code renders as this when you run the code (hit F5 on a PC)…

How Can We Help? Find out how Lone Peak Software can help you with Azure development.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close