I need some help creating a wizard in asp.net mvc. This wizard will contain about 7 or 8 steps. Here's how i've modeled the controller and i was hoping to get some feedback on whether this is the correct approach or to see if there are any better ways that someone here can recommend.
- I've created a separate view model class for each of the steps.
- I have a Wizard class which contains each of these seperate models + Properties like CurrentStep etc.
- I've created a separate view for each of the steps.
My controller looks like this
public class MyRegistrationController
{
[HttpGet]
public ActionResult Step1()
{
var wizard = TempData[WizardKey] as RegistrationWizard;
RegistrarRegisterVoterNewRegistrant model;
if (wizard == null || wizard.Step1Model == null)
{
wizard = new RegistrationWizard();
model = new NewRegistrant();
}
else
model = wizard.Step1Model;
wizard.CurrentStep = 1;
wizard.Step1Model = model;
TempData[WizardKey] = wizard;
return View("Step1", model);
}
[HttpPost]
public ActionResult Step1(NewRegistrant model)
{
var wizard = TempData[WizardKey] as RegistrationWizard;
if (wizard == null)
wizard = new RegistrationWizard();
if (!ModelState.IsValid)
return View("Step1", model);
wizard.Step1Model = model;
wizard.MaxCompletedStep = 1;
TempData[WizardKey] = wizard;
return RedirectToAction("Step2");
}
[HttpGet]
public ActionResult Step2()
{
var wizard = TempData[WizardKey] as RegistrationWizard;
PersonalInformation model;
if (wizard == null || wizard.Step1Model == null)
return RedirectToAction("Step1");
if (wizard.Step2Model == null)
model = new PersonalInformation ();
else
model = wizard.Step2Model;
wizard.CurrentStep = 2;
TempData[WizardKey] = wizard;
return View("Step2", model);
}
[HttpPost]
public ActionResult Step2(PersonalInformation model)
{
var wizard = TempData[WizardKey] as RegistrationWizard;
if (wizard == null || wizard.CurrentStep != 2 || wizard.Step1Model == null)
return RedirectToAction("Step1");
if (!ModelState.IsValid)
return View("Step2", model);
wizard.Step2Model = model;
wizard.MaxCompletedStep = 2;
TempData[WizardKey] = wizard;
return RedirectToAction("Step3");
}
}
Thanks!
I'm not selling this as a better approach, because it completely depends on your needs, but depending on the complexity of the wizard and your need to save to the DB on every step you could use something like this jquery Form to Wizard plugin to turn your form into a wizard. It is pretty straightforward and could reduce code/complexity in your controller
Your approach seems correct but might have some code repetitions between the steps actions. As an alternative and a little more generic approach you may checkout the following answer.