Pizza form submission

Update the HTTP Get page handler to display the list of Pizzas

Open the Pages/Pizza.cshtml.cs PageModel class file. Currently, the PizzaModel class handles the HTTP GET request with an empty OnGet page handler. Let's update this to display a list of pizzas from the PizzaService.

Update the OnGet page handler

Update the OnGet method as follows:

public void OnGet()
{
    pizzas = PizzaService.GetAll();
}

Add a List<Pizza> variable named pizzas to the PizzaModel class:

public List<Pizza> pizzas = new();

When the OnGet method is called, it will assign the results of the PizzaService.GetAll() method to the pizzas variable. This variable will be accessible to the Razor page template, where it will be written to the table listing the available pizzas.

These statements are referencing the PizzaService and Pizza classes, so you'll need to add the following using statements to the top of the PizzaModel class:

using RazorPagesPizza.Models;
using RazorPagesPizza.Services;

Use a utility method to format the Gluten Free information in the list

The IsGlutenFree property is a boolean value. You can use a utility method to format the boolean value as a string. Add the following utility method to the PizzaModel class:

C#Copy

public string GlutenFreeText(Pizza pizza) 
            => pizza.IsGlutenFree ? "Gluten Free" : "Not Gluten Free";

Add an HTTP POST page handler to the PageModel

Add the following method to the Pages/Pizza.cshtml.cs PageModel class.

public IActionResult OnPost()
{
    if (!ModelState.IsValid)
    {
        return Page();
    }
    PizzaService.Add(NewPizza);
    return RedirectToAction("Get");
}

The PizzaModel class now has an asynchronous OnPost page handler. OnPost executes when the user posts the Pizza page's form.

You can also use the optional Async naming suffix, OnPostAsync.

The OnPost 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.

  • PizzaService will handle the concern of HTTP requests and responses to the web API.

Bind the model

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

[BindProperty]
public Pizza NewPizza { get; set; } = new();

Last updated