Moving from Pages to Views
In this lesson, we will describe the differences between pages and views and how to reorganize a project by using controllers and Razor views instead of Razor pages.
We'll cover the following...
Razor pages versus Razor views
We already know that Razor pages have their own URL and retrieve all data they need to build the HTTP response, while Razor views are fed data by controllers. More specifically, controllers pass an object instance to the Razor views they invoke.
The @page
directive declares that a Razor file is a page, so views have no @page
directive at the beginning of the file. Instead, they declare the type of object they can receive from a controller. This way, one may access it in a type-safe way from inside the view code.
The object passed to a view is called a model or a ViewModel, so it should not be a surprise that the model type is declared with a @model
directive:
@model System.Collections.Generic.IList<MvcProject.ViewModels.Customer>
Like the @page
directive, the @model
directive must be placed at the beginning of the file. All types involved in the @model
declaration are usually specified with their full namespaces to avoid problems during code maintenance.
The model passed to a view is available in the view Model
property:
@foreach(var customer in Model){...}
In case a view contains just static HTML that must not be instantiated with data, the view doesn’t receive any model, so the @model
directive can be omitted.
Like Razor pages are placed in the Pages
project folder, views are placed in the Views
...