2013-03-07 28 views
2

我想就正確的設計模式或方法來解決我遇到的問題提出一些建議。堅持過濾器選擇的設計模式

基本上,在MVC3中,我有一個控制器,它有多個動作,都可以簡單地生成表格數據。大多數(但不是全部)操作應該有一個可選的年份值,該值根據選定年份過濾結果。目前,我通過查詢字符串接受年份值,但如果未提供(或無效),則默認爲當前年份。

我正在考慮創建一個簡單的操作方法,允許用戶通過選擇列表更改年份,將所選值(和當前頁面)發佈到將所選年份設置爲會話變量的操作(驗證之後)並將用戶重定向到他們所在的頁面。然後對於所有後續的請求,在控制器構造函數中,我會從會話變量中讀回一年,並將其存儲在局部變量中,然後可以在每個動作中使用該局部變量。

但是,我很猶豫要採取這種方法,因爲有許多引用(本網站上有許多引用)警告在控制器構造函數中使用會話變量。我可以繼續在每個方法中將查詢字符串參數傳遞給一年,但以下是一個操作中的代碼片段,顯示了我今年的驗證方式,並在每個操作中重複此操作似乎違反了DRY原則。有關如何完成此任務的任何建議?

public ActionResult FundsAppropriationList(int? year = null) 
{ 
    var fundsAppropriationListModel = new FundsAppropriationListModel(); 
    if (year != null && year >= 2000 && year <= 2099) 
    { 
    fundsAppropriationListModel.SelectedYear = (int)year; 
    } 
    else 
    { 
    fundsAppropriationListModel.SelectedYear = DateTime.Now.Year; 
    } 
    fundsAppropriationListModel.AvailableYearsList = new SelectList(_grantReviewServices.GetYearsForWhichReviewsExist().Select(x => new {value = x, text = x}), "value", "text"); 
    //... Remainder of model population here... 
    return PartialView("_FundsAppropriationList", fundsAppropriationListModel); 
} 

回答

2

爲什麼你需要在每個操作中複製該代碼?難道你不能把重複的代碼封裝到自己的方法中嗎?事情是這樣的:

public ActionResult FundsAppropriationList(int? year = null) 
{ 
    var fundsAppropriationListModel = new FundsAppropriationListModel(); 

    fundsAppropriationListModel.SelectedYear = AssignYear(year); 

    fundsAppropriationListModel.AvailableYearsList = new SelectList(_grantReviewServices.GetYearsForWhichReviewsExist().Select(x => new {value = x, text = x}), "value", "text"); 
    //... Remainder of model population here... 
    return PartialView("_FundsAppropriationList", fundsAppropriationListModel); 
} 

「複製」 代碼:

internal static int AssignYear(int? year = null) 
{ 
    if (year != null && year >= 2000 && year <= 2099) 
    { 
    return (int)year; 
    } 

    return DateTime.Now.Year; 
} 
+0

是啊,這就是我終於實現了。它只是輕微的「嗅覺」,我不得不在每個動作中調用相同的方法。我只是認爲可能有更好的方法來告訴控制器「每個動作都需要配置這些數據,所以當控制器被實例化時,爲我做這些」。無論如何,感謝您的反饋。 – bigmac 2013-03-08 17:31:16