Tuesday, January 19, 2010

Post, Redirect, Get Pattern in ASP.NET MVC


The ASP.NET MVC pattern tends to lead itself into a more simplified and "true" HTTP experience by re-introducing patterns that have been lost, or at least, not followed in many years. One such pattern is the Post, Redirect, Get (PRG) pattern in which it is "to help avoid duplicate form submissions and allow web applications to behave more intuitively with browser bookmarks and the reload button" (Wikipedia).

A normal ASP.NET Web Form Lifecycle has the following pattern

1. HTTP GET of "Create.aspx"
2. HTTP POST of "Create.aspx"
3. Validation Fails, "Create.aspx" is Re-Rendered
4. HTTP POST of "Create.aspx"
5. Item is created, "Create.aspx" is Re-Rendered with confirmation message

The major problems with this Postback pattern, is that hitting the Refresh button of your browser in steps 3 or 5 will re-post your submitted data. Step 5 is more of a problem as it could possibly re-submit that created information. Granted, there are steps that you can take to approach this problem, but this is how default ASP.NET Web Forms are treated.

Taking this same approach within ASP.NET MVC, can be achieved in the same manner by rendering a your "Create" view from your POST action. For example:

1. HTTP GET of "/products/create", "Create" view is rendered
2. HTTP POST to "/products/submit"
3. Validation Fails, "Create" view is rendered
4. HTTP POST to "/products/submit"
5. Item is created, "Confirm" view is rendered

As you'll notice, the same problems we had with ASP.NET Web Forms exists with ASP.NET MVC. The really nice option, is that ASP.NET MVC gives you a lot more "freedom" of how the workflow is processed. If we strictly follow the PRG pattern within ASP.NET MVC, it would look something like

1. HTTP GET of "/products/create", "Create" view is rendered
2. HTTP POST to "/products/submit"
3. Validation Fails, redirect to "/products/create", "Create" view is rendered
4. HTTP POST to "/products/submit"
5. Item is created, redirect to "/products/confirm", "Confirm" view is rendered

As you'll notice, where we previously could have had issues in step 3 or 5 before, we no longer have issues. If a user presses the Refresh button in either of those steps, they'll not get the lovely "Would you like to resubmit the form data" confirmation as featured below - instead, the page just reloads.






All detail information, please go ASP.NET MVC - Using Post, Redirect, Get Pattern

No comments:

Post a Comment