Lesson 2
Handling Different HTTP Methods
Introduction

Welcome to this lesson on handling different HTTP methods in ASP.NET Core Razor Pages. In the previous lesson, we introduced the concept of Page Handlers and learned about the importance and role of GET and POST handlers. In this lesson, we will dive deeper into how to handle these HTTP methods effectively in Razor Pages.

Our objectives for today are:

  • To understand the difference between GET and POST methods.
  • To learn how Razor Pages handle these methods by default.
  • To implement GET and POST handlers in Razor Pages with examples.
  • To combine GET and POST methods in a single Razor Page to manage data effectively.

Understanding how to handle different HTTP methods is crucial in web development as it helps in performing a variety of operations such as displaying data, submitting forms, and updating resources.

Understanding HTTP Methods in Razor Pages

Before we dive into examples, let's briefly review what GET and POST methods are.

GET Method:

  • Used to request data from a specified resource.
  • The data sent through GET is visible in the URL.
  • It's safe and idempotent, meaning that calling it multiple times has no side effects.
  • Commonly used to retrieve data, load webpages, etc.

POST Method:

  • Used to submit data to be processed to a specified resource.
  • Data sent through POST is included in the body of the request, not the URL.
  • Not idempotent; calling it multiple times can have different effects.
  • Commonly used to submit forms, upload files, etc.

In Razor Pages, the handlers for these methods are defined within the PageModel class. By default, Razor Pages automatically map HTTP methods to handler methods based on their naming. For example, OnGet handles GET requests, and OnPost handles POST requests.

Setting Up the Main Page

Let's start by setting up our main page that will manage three items and allow editing them. We'll set up a Razor Page to display item details.

Here's the code for App/Pages/Index.cshtml:

HTML, XML
1@page 2@model IndexModel 3<!DOCTYPE html> 4<html> 5<head> 6 <title>Index Page</title> 7</head> 8<body> 9 <h1>Welcome to the Index Page</h1> 10 <a href="/Edit/1">Edit Item 1</a><br /> 11 <a href="/Edit/2">Edit Item 2</a><br /> 12 <a href="/Edit/3">Edit Item 3</a><br /> 13</body> 14</html>

And the code for App/Pages/Index.cshtml.cs:

C#
1using Microsoft.AspNetCore.Mvc.RazorPages; 2 3public class IndexModel : PageModel 4{ 5 public void OnGet() 6 { 7 } 8}

This code sets up the main page that includes three links, each leading to a page for editing the corresponding item.

Implementing POST Requests: Client Code

Now, let's implement a Razor Page to handle POST requests for submitting form data. We'll use the Edit page for this. We will have the same page for editing every item, specifying the item's ID to differentiate the items.

Here's the code for App/Pages/Edit.cshtml:

HTML, XML
1@page "{id:int}" 2@model EditModel 3 4<form method="post"> 5 <div> 6 <label for="Name">Name</label> 7 <input id="Name" name="Name" asp-for="Name" required value="@Model.Name" /> 8 </div> 9 <button type="submit">Save</button> 10</form> 11 12@if (!string.IsNullOrEmpty(Model.Message)) 13{ 14 <p>@Model.Message</p> 15}

Here is what happens here:

  • The @page "{id:int}" directive specifies that the page expects an id parameter of type integer - the item's ID.
  • The form uses the POST method to send the data to the server.
  • The asp-for="Name" attribute binds the input to the Name property in the EditModel class.
  • The "Submit" button submits the form, sending the POST request to the server.
  • The @if (!string.IsNullOrEmpty(Model.Message)) { <p>@Model.Message</p> } section checks if the Message property is not empty and displays it as a paragraph if it's present.
Implementing POST Requests: Server Code

After we set up the client code, here is the server code for App/Pages/Edit.cshtml.cs:

C#
1using Microsoft.AspNetCore.Mvc; 2using Microsoft.AspNetCore.Mvc.ModelBinding; 3using Microsoft.AspNetCore.Mvc.RazorPages; 4using Microsoft.Extensions.Logging; 5using System.Collections.Generic; 6using System.Linq; 7 8public class EditModel : PageModel 9{ 10 private static readonly Dictionary<int, string> NameStore = new(); 11 12 [BindProperty] 13 public string Name { get; set; } 14 15 public string Message { get; set; } 16 17 public void OnGet(int id) 18 { 19 NameStore.TryGetValue(id, out var name); 20 Name = name; 21 } 22 23 public IActionResult OnPost(int id) 24 { 25 NameStore[id] = Name; 26 Message = "Successfully saved!"; 27 return Page(); 28 } 29}

Here is a brief explanation:

  • The OnPost method handles POST requests and saves the submitted Name to a dictionary (NameStore), based on the specified item's ID that we received in the POST request.
  • If the form submission is successful, a success message is displayed.
  • After the POST request is processed, the page is reloaded to show the updated data.
Combining GET and POST in a Single Page

Next, we'll combine GET and POST methods in a single Razor Page to manage both reading and updating data seamlessly.

Here's how the combined code in Edit.cshtml.cs looks:

C#
1public void OnGet(int id) 2{ 3 NameStore.TryGetValue(id, out var name); 4 Name = name; 5} 6 7public IActionResult OnPost(int id) 8{ 9 NameStore[id] = Name; 10 Message = "Successfully saved!"; 11 return Page(); 12}
  • The OnGet method loads the data for the specified id when the page is requested via a GET method.
    • For example, initially, visiting /Edit/1 with a GET request will call OnGet(1) and display the data.
  • The OnPost method saves the updated data for the specified id when the form is submitted.
    • For example, submitting the form will send a POST request to the same URL, calling OnPost(1) for the first item and updating the data store.
Lesson Summary

In this lesson, we covered the basics of handling HTTP methods in Razor Pages. To recap:

  • We discussed GET and POST methods and their roles in web applications.
  • We explored how to handle GET requests to display data.
  • We learned how to handle POST requests to submit form data.
  • We combined GET and POST methods on a single page to manage data more effectively.

Remember, handling HTTP methods correctly ensures your web application can interact with users in a meaningful way. Practice writing and testing GET and POST handlers using the exercises provided.

Up next, we will be diving into more advanced aspects of Razor Pages, so stay tuned!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.