2014-01-13 57 views
1

我有一个MVC应用程序,其中有一个或多个工作流程,非常相似但不同的工作流程。例如:MVC工作流模型状态

  • 步骤1
  • 步骤2
    • 步骤2a
    • 步骤2b(在步骤2a &状态条件)
  • 工序(上步骤2 &状态条件) 3
  • 表面处理

每个步骤都有与之相关的特定验证。目前,该行动是建立东西如下:

public controller Test 
{ 
    public ActionResult Step1() 
    { 
     // validation (10-30 lines) 

     // Store against model 

     return RedirectToAction("Step2"); 
    } 

    public ActionResult Step2() 
    { 
     // validation (10-30 lines) 

     // Store against model 

     return someCondition ? RedirectToAction("Step2a") : RedirectToAction("Step3"); 
    } 

    public ActionResult Step2a() 
    { 
     // validation (10-30 lines) 

     // Store against model 

     return RedirectToAction("Step2"); 
    } 
} 
  1. 有没有这样做return GetNextStep()的一种方式?我在想一个状态机,但我不确定这是否是由于条件元素和状态(以及状态应该在哪里生存?模型内部还是独立状态对象?)最好的模式。
  2. 什么是验证每一步的最佳方式?
+0

你是否在每一步使用不同的模型? –

+0

目前是。但我期待重新建模使用单个模型并仅绑定到正确的属性。 –

+0

所以你可以用你需要的5个步骤构建一个包含所有字段的模型。并且在每一步中,您都可以将控件传递给控制器​​并返回下一个步骤视图。 –

回答

1

用5个步骤创建一个包含所有字段的模型。

public class FullForm 
{ 

// fields for step 1 

public string FirstFieldOfStep1 {get; set;} 
.... 

// put as many fields are there in step 1 

//Fields For second step 

public string FirstFieldOfStep2 {get; set;} 

// all your conditional fields goes here 
.... 


//Fields For Third step 

public string FirstFieldOfStep3 {get; set;} 


} 

现在在您的视图中,您可以有5个不同的HTML页面(每个步骤)。

并在您的主视图(让名称为MainForm.cshtml)您可以有一个类似的开关案例。

@{ 

    switch(find which field is yet to be filled) 
    { 
    case(if FirstFieldOfStep1 is null) : @Html.RenderPartial("Step1.cshtml"); 

    case(if FirstFieldOfStep2 is null) : @Html.RenderPartial("Step2.cshtml"); 

    case(if FirstFieldOfStep3 is null) : @Html.RenderPartial("Step3.cshtml"); 

    } 
} 

在您的Step2.cshtml您可以检查条件并相应调用其他两个视图。

在你的控制器中,你可以做到这一点。

public controller Test 
{ 
    [HttpPost] 
    public ActionResult Step1(FullForm fullFormDetails) 
    { 
     if(all the required fields are available with new values) 
     { 
      //save in database and proceed. 
     } 
     else 
     { 
     return View ("MainForm",fullFormDetails) 
     } 

    } 

} 

所以基本上你在这里做的是你正在收集点点在你的控制器每次都传递整个数据视图的形式,细节位,因此,它可以使那些需要到下一页收集数据。所以最后你只会保存整个表单一次。

您可以在MVC中自定义验证属性,以便您不需要每次在控制器中验证表单。您可以在这里查看构建自定义属性并根据您的应用程序对其进行相应更改,这是一种干净的方法。 Custom attribute in MVC

+1

我没有使用Visual Studio,所以查找错别字。 –