Post-Redirect-Get (PRG) Pattern Example in ASP.NET Core

SPONSOR AD

Post-Redirect-Get (PRG) Pattern Example in ASP.NET Core

In this article, I will discuss the Post-Redirect-Get (PRG) Pattern Example in the ASP.NET Core MVC Application with Examples using TempData. Please read our previous article discussing TempData in ASP.NET Core MVC Application.

What is the Post-Redirect-Get (PRG) Pattern?

The Post-Redirect-Get (PRG) pattern is a web development design pattern that helps prevent duplicate form submissions and ensures a more user-friendly web application experience. It’s especially relevant when a user submits form data to a server via an HTTP POST request.

Basic Workflow of PRG Pattern:
  • POST Request: The user submits a web form; this sends an HTTP POST request to the server.
  • Server Processing: The server processes the POST request, typically involving data manipulation like updating a database.
  • Redirection: Instead of sending a response directly after processing the POST request, the server sends an HTTP redirect (HTTP status code 302 or 303) to the client.
  • GET Request: Upon receiving the redirect response, the client makes an HTTP GET request to the specified URL.
  • Final Response: The server responds to the GET request with the final page, which could be a confirmation, result page, or another view.
Post-Redirect-Get (PRG) Pattern using TempData in ASP.NET Core MVC

The Post-Redirect-Get (PRG) pattern is a web development design pattern that helps prevent duplicate form submissions and ensures that the web page behaves correctly when the user refreshes it. In ASP.NET Core MVC, the PRG pattern can be implemented using TempData, which is a way to pass data between controllers and views.

Create a Model

First, you need a model to bind your form data. So, create the following MyModel.cs class within your Models folder:

SPONSOR AD
namespace FirstCoreMVCWebApplication.Models
{
    public class MyModel
    {
        public string Name { get; set; }
        public string Email { get; set; }
        // Add other properties as needed
    }
}
Create a Controller

In your controller, create two actions – one for displaying the form (HTTP GET) and another for processing the form (HTTP POST). So, modify the Home Controller as follows:

using FirstCoreMVCWebApplication.Models;
using Microsoft.AspNetCore.Mvc;
namespace FirstCoreMVCWebApplication.Controllers
{
    public class HomeController : Controller
    {
        // GET: Display the form
        public IActionResult Index()
        {
            return View();
        }

        // POST: Process the form
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult SubmitForm(MyModel model)
        {
            if (ModelState.IsValid)
            {
                // Process your model here (e.g., save to database)

                // Store a message in TempData
                TempData["SuccessMessage"] = "Form submitted successfully!";

                // Redirect to a GET method
                return RedirectToAction(nameof(Success));
            }

            // If model state is invalid, show the form again
            return View("Index", model);
        }

        // GET: Success page
        public IActionResult Success()
        {
            return View();
        }
    }
}
Create the Views

You’ll need a view for the form and another for the confirmation.

Index.cshtml (Form View):

Create a view with the name Index.cshtml within the Views/Home folder, and then copy and paste the following code:

@model FirstCoreMVCWebApplication.Models.MyModel

<form asp-action="SubmitForm" asp-controller="Home" method="Post">
    <div asp-validation-summary="ModelOnly"></div>
    <div>
        <label asp-for="Name"></label>
        <input asp-for="Name" />
        <span asp-validation-for="Name"></span>
    </div>
    <div>
        <label asp-for="Email"></label>
        <input asp-for="Email" />
        <span asp-validation-for="Email"></span>
    </div>

    <button type="submit">Submit</button>
</form>
Success.cshtml (Success View)

Display the success message. Create a view with the name Success.cshtml within the Views/Home folder, and then copy and paste the following code:

@{
    var message = TempData["SuccessMessage"] as string;
}

@if (!string.IsNullOrEmpty(message))
{
    <div>@message</div>
}

<a asp-action="Index">Back to Form</a>
Explanation
  • Index Action: Displays the form to the user.
  • SubmitForm Action: Process the form submission. If the model is valid, it processes the data (like saving to a database) and then uses TempData to store a success message before redirecting to the Success action.
  • Success Action: Displays a success message to the user. The message is retrieved from TempData.

By using the PRG pattern, if the user refreshes the success page, it doesn’t resubmit the form data. Instead, it simply refreshes the view of the success message. TempData is ideal for this scenario as it keeps data for the duration of a single redirect and is then automatically discarded.

Now, run the application, and it should display the following page where you need to enter the Name and Email and click on the Submit button as shown in the image below:

Post-Redirect-Get (PRG) Pattern Example in the ASP.NET Core MVC

SPONSOR AD

Once you click on the Submit button, it will open the following page and display the successful message as shown in the below image:

Post-Redirect-Get (PRG) Pattern Example in the ASP.NET Core MVC

If you verify the Network tab, it will show the following: It will issue a 303 request and then redirect to the Success page with a 200 status code.

Post-Redirect-Get (PRG) Pattern Example in the ASP.NET Core MVC

Now, if you refresh the page, then you will see that the page has not been submitted again.

Advantages of PRG:
  • Avoids Duplicate Submissions: Refreshing the browser after a POST request typically resends the form data, potentially causing duplicate submissions (like double orders in e-commerce). With PRG, a refresh after the final step results in a repeat of the GET request, not the form submission.
  • Cleaner URLs: After the process is complete, the URL in the browser reflects the GET request, not the original POST, which is generally cleaner and more user-friendly.
  • Bookmarking and Sharing: The final GET request URL can be bookmarked or shared, which isn’t advisable for a URL resulting from a POST request.
  • Improved User Experience: It provides a smoother user experience, reducing confusion caused by browser warnings about form resubmissions when the page is refreshed.

In the next article, I will discuss Routing in ASP.NET Core MVC Applications with Examples. In this article, I try to explain the Post-Redirect-Get (PRG) Pattern Example in the ASP.NET Core MVC Application with examples. I hope you enjoy this Post-Redirect-Get (PRG) Pattern Example in the ASP.NET Core MVC article.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *