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 ofRazorPagesPizza.Pages
.
OnGet() , OnPost() and others are "standard" functions and must be used as such, any other name will not work!
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
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 calledPizzaService
. ThePizzaService
will handle the concern persisting the data.
We will add the OnPost() handler to the code shortly
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; }
Last updated