ASP.NET Core Razor Pages use a page-focused programming model. A page .cshtml and its associated page model .cshtml.cs
In the pages folder, create a page called News.cshtml. Do so via:
On a MAC use
This will create a .cshtml and associated page model.cshtml.cs file.
The @page directive must be the first line of the a page and is unique to Razor Pages (ie not seen in the MVC approach). It makes the page itself work as the actions which in the MVC approach would be handled by the controller.
The second directive @model points to the model for the page - the Page Model.
Notice that the Model inherits from the PageModel class and that the name of the Model matches that of the Page but with the suffix of Model, in the above example PageModel. By inherting from PageModel the model gains functionality such as httpContext, request and response values and TempData which form 'actions' for the model.
By default pages will come with an OnGet() method. This is an 'action' or handler for HTTP GET calls against the page. As well as OnGet() developers could us OnPost() where data for example is sent from a HTML form of method POST.
ViewData is a container for sending data from the PageModel to the Page.
ViewData values can be declared in the Page ie
ViewData values can also be declared in the Page Model ie
In either case the ViewData value is included in the Page with:
In the Page Model the [ViewData] attribute can also be used to add values:
With Razor Pages you are not limited to ViewData for passes data to the Page. Variables that have an accessor modifier of public are available to the page as properties of the Model.
With the public property of the Model declared in the Page Model, it can then be used in the Page as follows:
Notice there is no need to reference Model.latestNews as the model is understood by the page via the @model directive.