I’ve been searching for this topic on SO and it’s quite a headache not finding one.
I had developed a website for some time already and found that the current problem is that after postback, if the submission has any error and the user is redirect back to the form, the form values are all gone.
Is there a good way/flow/design to implement such that after postback the values are retained? Also I need to consider default values, values from database and the values from postback – so which one takes priority?
In addition, I wish to follow Post-Redirect-Get and use back the same form.
What I had thought of was:
- Identify each form with a unique ID
- When submitted, save all data into the Session using the form’s unique ID
- When the form is requested again, show the values from the form.
- If submitted successfully, clear the data in session.
Here’s my usual workflow:
After a POST fails I output form right away without redirecting to the initial form page. This is very easy to accomplish with any decent template system. You can then re-populate the form with the POST’ed data.
If the form is tied to a view (as part of an MVC pattern) you can initialize default values and load models from the database (to populate drop-down menus, etc.) – reuse the entire display / fronted logic.
If the current code base is using a redirect you can simply
include()the desired form/view file at a serendipitous point in post-back processing.So how does it work? In a nutshell: