在ASP.NET MVC 4中创建带有友好URL的向导

3

我正在开发一个ASP.NET MVC 4应用程序,其中需要嵌入一个向导。这个向导包含三个屏幕。我需要将它们的URL映射到:

/wizard/step-1
/wizard/step-2
/wizard/step-3

在我的WizardController中,我有以下动作:
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);
}

虽然这种方法可行,但我的问题是浏览器URL不会更新。我该如何发布来自步骤的值并将用户重定向到具有不同数据模型的新URL?

谢谢!

1个回答

2

在您的向导视图中,每次调用Html.BeginForm()时,请确保调用一个重载版本,该版本接受所需的路由或所需的控制器、操作和其他路由参数。例如,在Step1.cshtml中:

@using (Html.BeginForm("Step-2", "MyWizard")) {
    // put view stuff in here for step #1, which will post to step #2
}

这将使目标URL“漂亮”,但它不会修复动作名称本身的“丑陋”。为了解决这个问题,MVC中有一个功能可以将动作方法“重命名”为几乎任何你想要的名称:

[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
}

假设该应用程序使用默认的MVC路由(控制器/操作/ID),每个步骤都会有自己的URL。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接