PageModel Binding

OnGet() handler

Below is a new PageModel class file contains the following C# code:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace RazorPagesPizza.Pages
{
    public class PizzaModel : PageModel
    {
        public void OnGet()
        {
        }
    }
}
  • A Razor page's PageModel class file defines any page handlers for HTTP requests sent to the page, and data used to render the page.

  • The PageModel keeps those concerns separate from the Razor page, your app more modular, and easier to maintain.

  • By convention, the PageModel class is named [PageName]Model and resides in the same namespace as the Razor page.

  • In this case, the PizzaModel class in the namespace of RazorPagesPizza.Pages.

The PageModel keeps those concerns separate from the Razor page, your app more modular, and easier to maintain.

Currently, the PizzaModel class handles the HTTP GET request with an empty OnGet page handler. You can add handlers for any HTTP verb. The most common handlers are:

  • OnGet to initialize state needed for the page.

  • OnPost to handle form submissions.

The Pizza page contains a form and therefore requires an HTTP POST page handler.

HTTP POST page handlers in a PageModel

The OnPostAsync page handler needs to perform the following tasks for this app:

  • Verify the user-submitted data posted to the PageModel is valid.

  • If the attempted PageModel changes are invalid, the Pizza page is presented again to the user. A message is displayed clarifying the input requirements.

  • If the PageModel update is valid, then data changes are passed to a service called PizzaService. The PizzaService will handle the concern persisting the data.

We will add the OnPost() handler to the code shortly

If the attempted PageModel changes are invalid, the Pizza page is presented again to the user.

Bind the model

The PizzaModel class needs access to the Pizza model. It will validate and pass Pizza entries from the Pizza form. It does so by using the [BindProperty] attribute in the following code:

[BindProperty]
public Pizza NewPizza { get; set; }

Binding to properties can reduce the amount of code you have to write. Binding reduces code by using the same property to render fields such as in

<input asp-for="Pizza.Name">.

Last updated