這篇文章結合Asp.net MVC和WF4.0實現一個簡單的使用者多步註冊。使用者註冊分了四步驟。流程圖如下:
第一步:填寫個人資訊:
第二步:填寫職位資訊:
第三步:填寫學曆資訊:
第四步:填寫聯絡資訊:
第五步驟:完成
WF4.0狀態機器如:
每一步點擊Next跳到下一步,點擊Back回到上一步。
實現:
第一步:建立一個ASP.NET MVC Application和一個Workflow的ActivityDesignerLibrary項目,在mvc項目的Model檔案夾下添加一個User。代碼如下:
1 public class User
2 { //個人資訊
3 [Required(ErrorMessage = "姓名不可為空")]
4 [StringLength(20, ErrorMessage = "姓名長度不能超過20個字元")]
5 public string Name { get; set; }
6 public int? Age { get; set; }
7 //職位資訊
8 [Required(ErrorMessage = "職位不可為空")]
9 public string Post { get; set; }
10 public int? Salary { get; set; }
11 //學曆資訊
12 [Required(ErrorMessage = "畢業院校不可為空")]
13 public string University { get; set; }
14 public int? GraduationYear { get; set; }
15 //聯絡資訊
16 [Required(ErrorMessage = "郵件不可為空")]
17 [RegularExpression(@"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" + @"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z]" + @"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$", ErrorMessage= "郵件格式不正確")]
18 public string Email { get; set; }
19 public int? Mobile { get; set; }
20 }
21
第二步:在Controllers中添加一個控制類,代碼如下:
1 public class UserController : Controller
2 {
3 //
4 // GET: /User/
5 #region Declarations
6 static WorkflowUtil wrkFlw = null;
7 string page="Step1";
8 public User userObj;
9 #endregion
10 #region Process action method
11 public ActionResult Process(string nextButton, string backButton)
12 {
13 if (wrkFlw == null )
14 {
15 wrkFlw = new WorkflowUtil();
16 }
17 if ((nextButton != null))
18 {
19 page = wrkFlw.RunWorkflow("Next");
20 return View(page, userObj);
21 }
22 else if (backButton != null)
23 {
24 ModelState.Clear();
25 page = wrkFlw.RunWorkflow("Prev");
26 return View(page, userObj);
27 }
28 else
29 return View(page, userObj);
30 }
31 #endregion
32 #region Events
33 protected override void OnActionExecuting(ActionExecutingContext filterContext)
34 {
35 userObj = (User)TempData["User"];
36 if (userObj == null) userObj = new User();
37 TryUpdateModel(userObj);
38 if (TempData["CurrentPage"] != null) page = TempData["CurrentPage"].ToString();
39 }
40 protected override void OnResultExecuted(ResultExecutedContext filterContext)
41 {
42 TempData["User"] = userObj;
43 TempData["CurrentPage"] = page;
44 }
45 #endregion
46 public ActionResult Index()
47 {
48 return View();
49 }
50 }
第三步:在方法Process上選擇添加視圖,如選擇:
如此共產生五個view頁面:step1.step2,step3,step4,step5,Final。
第四步:設計狀態機器工作流程。這裡只示範step1的設定,如:
總結:使用WF完美結合asp.net mvc實現這個功能。
代碼:/Files/zhuqil/mvc.rar