2012-09-12 116 views
0

我有一個模型,其中有一個下拉的參考數據的列表。參考數據基於當前用戶。因此,用戶A看到了分配給他的記錄,用戶B可以看到不同的記錄。關鍵是,參考數據基於userId。模型訪問會話變量?

的用戶ID是在會話。模型是否有訪問會話變量的方法? SelectionList的創建內置於模型中。所以,我可以把用戶ID作爲構造函數的參數 - 但我需要在該模型中的所有構造函數。似乎重複工作。我寧願模型要能說,「啊,當前用戶是用戶1」,但它的自我。

可能嗎?或者我有設計缺陷?

+0

樣本編碼將是有益的。 – VIRA

+1

檢查此,它可以幫助你:http://stackoverflow.com/questions/735133/asp-net-mvc-how-to-access-session-data-in-places-other-than-controller-and-vie – 2012-09-12 07:13:09

回答

1

如何像這樣

public class WibbleModelBuilder 
{ 
    private int _userId; 
    private WibbleRepository _repo; 
    public WibbleModelBuilder(WibbleRepository wibbleRepository, int userId) 
    { 
     _repo=wibbleRepository; 
     _userId=userId; 
    } 

    public WibbleModel Build() 
    { 
     var model = new WibbleModel(); 
     model.LookupList = _repo.GetLookupForUser(_userId); 
     return model; 
    } 
} 

現在你可以在你的控制器WibbleModelBuilder創建您並通過您的存儲庫和用戶ID到構造。您的模型現在只是一個非常簡單的數據對象

public class WibbleModel 
{ 
    public IList<ReferenceData> LookupList { get; set;} 
}