I have a project with a form that is completed over several parts. E.g. Part 1 might include your name, and part 2 your address.
In MVC I have several views which represent each of the parts and one model to hold all the form data.
I would like to save the form data at the completion of each part, and retrieve the saved record on the next part (so that the whole model is available at each stage).
I am using Post-Redirect-Get to avoid the 'form may be resubmitted' warnings from browsers using the back and forward buttons.
Controller code
[HttpGet]
[Route("Form/Part/{id}")]
public ActionResult Part(int id, int? recordId)
{
var model = new MyVM();
if(recordId.HasValue) {
// get record from DB
// map record to 'model'
}
return View("Form.{id}", model);
}
[HttpPost]
[Route("Form/Part/{id}")]
public ActionResult Part(int id, MyVM model)
{
// map model to entity
// save/update entity
return RedirectToAction($"Form/Part/{id + 1}", new { recordId = recordId })
}
My question is how best to retain the ID of the newly created / updated record and pass it to the next form part.
Whilst passing the recordId
as a routeValue
works, it breaks when I use the browser back button as the recordId
in the querystring is lost.
I have considering storing this in the session perhaps, but don't really want to bring the HttpContext
into play if I don't have to for testing reasons.
Is there a recommended way to achieve this kind of thing? Any thoughts on the various ways to keep track of the current record would be greatly appreciated.
You can either use the TempData or Session to pass Data between requests.
I Would create a big class / object with all the fields from the wizard, throw it in the session eg key "MyWizardData" and retrieve it in the other parts of the wizard.
After
you have the ID, throw it in the session and grab it back in the next action.
If you dont want to use the session, get the id after save / update and store it in a field in the database in the user table. Or just store the UserId with your created entity row. Then you can grab it in any action.