[英]MVC Workflow Model State
我有一個MVC應用程序,其中包含一個或多個工作流程,它們非常相似但又不同。 例如:
每個步驟都有與之相關的特定驗證。 當前,操作已設置為以下內容:
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");
}
}
return GetNextStep()
? 我當時在考慮狀態機,但是由於條件元素和狀態( 狀態應該在哪里?在模型內部還是在單獨的狀態對象之內? ),我不確定這是否是最佳模式。 創建一個模型,並在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中自定義驗證屬性,這樣就不必每次都在控制器中驗證表單。 您可以在這里查看如何構建自定義屬性,並為您的應用程序相應地對其進行更改,這是一種干凈的方法。 MVC中的自定義屬性 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.