Creating a wizard with friendly urls in ASP.NET MVC 4
I am working on an ASP.NET MVC 4 application. This application requires a wizard. The wizard contains three screens. I need their urls to map to:
/wizard/step-1 /wizard/step-2 /wizard/step-3
In my WizardController, I have the following actions:
public ActionResult Step1()
{
var model = new Step1Model();
return View("~/Views/Wizard/Step1.cshtml", model);
}
[HttpPost]
public ActionResult AddStep1(Step1Model previousModel)
{
var model = new Step2Model();
model.SomeValue = previousModel.SomeValue;
return View("~/Views/Wizard/Step2.cshtml", model);
}
[HttpPost]
public ActionResult AddStep2(Step2Model previousModel)
{
var model = new Step3Model();
return View("~/Views/Wizard/Step3.cshtml", model);
}
While this approach works, my problem is that the browser url is not updating. How can I send values from a step and redirect the user to a new url with a different data model?
Thank!
source to share
In each of the views of the wizard where you call Html.BeginForm()
, make sure you are invoking an overload that takes either the desired route or the required controller, action, and other routing parameters. For example, in Step1.cshtml:
@using (Html.BeginForm("Step-2", "MyWizard")) {
// put view stuff in here for step #1, which will post to step #2
}
This will make the target URL "pretty", but it will not fix action names that are "ugly". To fix this, MVC has a function that will "rename" an action method to almost anything you want:
[HttpPost]
[ActionName("step-2")] // this will make the effective name of this action be "step-2" instead of "AddStep1"
public ActionResult AddStep1(Step1Model previousModel)
{
// code here
}
Assuming the application is using the default MVC route (controller / action / id), each step will have its own URL.
source to share