天天看點

愛上MVC3系列~将公用的子產品提到PartialView

事實是這樣的,這個項目它有産品,使用者,使用者要買産品,這時産生了訂單,而這三個對象都有被評論的功能,這時評論對象Review就産生了,我們要設計一個視圖,它來實作對三個對象的評論功能,沒有人會希望同樣的功能被重複的開發,相同的代碼出現的不同的地方,這當然也違背了DRY原則,是以,我們需要抽象,我們需要封裝,我們需要對問題進行面向對象的分析. 第一部:将對象抽象出來,找來不變的與變化的屬性 product,user,order共同作用于reviews,我們來看一下review的實體結構

1     /// <summary>
 2     /// 評論對象
 3     /// </summary>
 4     public class Review
 5     {
 6         public long ID { get; set; }
 7         /// <summary>
 8         /// 被評論對象的類型
 9         /// </summary>
10         public int ObjType { get; set; }
11         /// <summary>
12         /// 被評論對象的ID
13         /// </summary>
14         public long ObjID { get; set; }
15         [Required]
16         public string Title { get; set; }
17         [Required]
18         public string Content { get; set; }
19         [Required]
20         public DateTime CreateDate { get; set; }
21      
1     /// <summary>
2     /// 系統主要對象的類型
3     /// </summary>
4     public enum ObjectType
5     {
6         User,
7         Product,
8         Order
9      

  而事實上,除了ObjType與ObjID之外,其它屬性對于三大對象來說都是相同的,這時,我們可給在設計視圖時,将objtype與objid以參數的形式告訴review,代碼如下: 

1         /// <summary>
 2         /// 評論公用視圖
 3         /// </summary>
 4         /// <returns></returns>
 5         public ActionResult Review(int? objID, int? objType)
 6         {
 7             return View(new Review
 8             {
 9                 ObjID = objID ?? 0,
10                 ObjType = objType ?? 1,
11                 Content = "",
12                 Title = "",
13             });
14      

最後通過送出表單将objid和objtype的值post到實體中,然後根據objtype來确實操作完成後頁面所重定向的位址. 代碼如下: 

1         [HttpPost]
 2         public ActionResult Review(Review entity)
 3         {
 4             if (ModelState.IsValid)
 5             {
 6                 //資料操作邏輯
 7                 //code...
 8                 switch (entity.ObjType)
 9                 {
10                     case (int)ObjectType.User:
11                         return RedirectToAction("Index", "User", new { id = entity.ObjID });
12                     case (int)ObjectType.Product:
13                         return RedirectToAction("Index", "Product", new { id = entity.ObjID });
14                     case (int)ObjectType.Order:
15                         return RedirectToAction("Index", "Order", new { id = entity.ObjID });
16                     default:
17                         break;
18                 }
19             }
20             else
21                 ModelState.AddModelError("", "請認真填寫...");
22             return View();
23      

繼續閱讀