Asp.net mvc向导 - 需要一些指导

时间:2011-08-31 20:46:50

标签: asp.net-mvc-3 razor wizard

我需要一些帮助在asp.net mvc中创建一个向导。 该向导将包含大约7或8个步骤。 以下是我对控制器进行建模的方式,我希望得到一些关于这是否是正确方法的反馈,或者看看有没有更好的方法可以推荐给人。

  • 我为每个步骤创建了一个单独的视图模型类。
  • 我有一个向导类,其中包含每个单独的模型+像CurrentStep等属性。
  • 我为每个步骤创建了一个单独的视图。

我的控制器看起来像这样

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");
    }
}

谢谢!

2 个答案:

答案 0 :(得分:2)

您的方法似乎是正确的,但步骤操作之间可能会有一些代码重复。作为替代方案和更通用的方法,您可以查看following answer

答案 1 :(得分:1)

我不是将它作为更好的方法出售,因为它完全取决于您的需求,但取决于向导的复杂性以及您在每一步都需要保存到数据库的需要使用类似这个jquery Form to Wizard plugin的东西将你的表单变成一个向导。它非常简单,可以降低控制器中的代码/复杂性