我一直在尋找mvc的視圖模型,我正在尋找最好的方法來完成它們。我讀過大量不同的文章,但沒有一篇看起來像「最好的方式」那樣清晰。到目前爲止,例如,我可能有一個客戶模型具有以下屬性:asp.net mvc viewmodels。他們應該包含多少邏輯(如果有的話)
- 名
- 姓
- 標題
- 位置
如果位置是一個外鍵的位置數據庫中的表。
我希望能夠編輯此客戶,但只能輸入名字,姓氏和位置。我對編輯中的標題不感興趣。所以在我看來,我需要通過一個客戶和一個選定的列表。
現在從我讀過的書中我有以下選項(可能還有更多)。
所以我的問題基本上哪個是最好的?
1)
添加一個選擇列表中ViewData["Location"]
和剛剛創造客戶的強類型的看法?
2)
創建其中I通過一個客戶和選擇列表的圖模型(數據訪問在控制器完成):
public class ViewModelTest
{
public Customer Customer { get; set; }
public SelectList Locations { get; set; }
public ViewModelTest(Customer customer, SelectList locations)
{
Customer = customer;
Locations = locations;
}
}
3)
創建視圖模型我在那裏傳遞客戶和位置列表,並在視圖模型中創建選擇列表。
public class ViewModelTest
{
public Customer Customer { get; set; }
public SelectList Locations { get; set; }
public ViewModelTest(Customer customer, List<Location> locations, string selectedLocation)
{
Customer = customer;
Locations = new SelectList(locations, "LocationID", "LocationName", selectedLocation);
}
}
4)
傳遞一個客戶和倉庫,做在視圖模型的數據訪問。
public class ViewModelTest
{
public Customer Customer { get; set; }
public SelectList Locations { get; set; }
public ViewModelTest(Customer customer, IRepository repository, string selectedLocation)
{
Customer = customer;
Locations = new SelectList(repository.GetLocations(), "LocationID", "LocationName", selectedLocation);
}
}
5)
只需我需要的屬性創建視圖模型:
public class ViewModelTest
{
public string FirstName { get; set; }
public string LastName { get; set; }
public SelectList Locations { get; set; }
public ViewModelTest(Customer customer, SelectList locations)
{
FirstName = customer.FirstName;
LastName = customer.LastName ;
Locations = locations;
}
}
6)
還是上面的或其它方式的一些其它組合。
歡迎任何意見。