Saturday, November 08, 2008

PRG Pattern - You're Already Doing it

Have you ever had this message dialog asking about resubmiting the data when you try to refresh a web page? This actually happen after submitting a form or enter your login information.

One of the good practices when developing web application is to redirect the user after a successful posting request. This practice is refereed as PRG pattern (Post/Redirect/Get). The target is to avoid duplicate post requests from the client and providing a smooth navigation through the web application.

What actually happen in PRG is that the browser try to send an HTTP 303 redirect request along with HTTP "Location" header. It's nice to know that something you're used to make as a default practice is actually a pattern. The following is a sample code in ASP.NET MVC illustrating the usage of the pattern:

[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
{
    if (ModelState.IsValid)
    {
        MembershipUser currentUser = Provider.GetUser(User.Identity.Name, true /* userIsOnline */);

        // Attempt to change password
        bool changeSuccessful = currentUser.ChangePassword(currentPassword, newPassword);

        if (changeSuccessful)
           return RedirectToAction("ChangePasswordSuccess"); //PRG Pattern recommendation
    }

    return View();
}

0 comments: