0

那麼,我們來看一個例子。我有一個看起來像這樣的客戶視圖模型:在哪裏放置與視圖數據無關的額外視圖數據

public class CustomerViewModel { 
    public string Name {get; set;} 
    public int CustomerTypeId {get; set;} 
} 

在UI上需要下拉客戶類型。爲了填充這些,需要到業務層或數據層並獲取這個客戶類型列表。

在我看來,這個邏輯並不真正屬於CustomerViewModel,因爲它不是真正的客戶數據;只有CustomerTypeId是。所以我的問題是,在一般情況下(不一定在.net MVC中,但是MVC視圖模型概念的一般實踐)人們把這些數據訪問了嗎?

在視圖模型本身中有一個名爲GetCustomerTypes()的函數是否可以接受?

public class CustomerViewModel { 
    public string Name {get; set;} 
    public int CustomerTypeId {get; set;} 

    public List<CustomerType> GetCustomerTypes() { ... } 
} 

我應該在業務層或助手中創建一個類/方法,並在視圖中手動導入代碼以訪問此函數嗎?在我看來,這將是代碼混亂的觀點,並不屬於那裏。

@{ 
    using My.App.CustomerTypeHelper; 
    var helper = new CustomerTypeHelper(); 
    var customerTypes = helper.GetCustomerTypes(); 
} 

... 

@Html.DropDownFor(x => x.CustomerTypeId, customerTypes) 

全球HTML幫助緩解這個問題在.net了一點,但我要尋找一個更具全球性的解決方案概念,我可以適用於PHP代碼等也。 PHP不具備乾淨地擁有靜態類的能力,可以使用擴展方法將其分爲小型組織單元。所以任何全球幫手都可能變得龐大而醜陋。

回答

2

您應該在模型中包含List<CustomerType>,但不要在模型中實現函數。改爲設置來自控制器的數據。

事情是這樣的:從控制器

public class CustomerViewModel { 
    public string Name {get; set;} 
    public int CustomerTypeId {get; set;} 

    public List<CustomerType> CustomerTypes { get; set; } 
} 

分配數據視圖模型:

var model = new CustomerViewModel(); 
model.CustomerTypes = Customer.GetCustomerTypes(); 
+0

這似乎會變得更加討厭。這會導致在更多的實際場景中有大量的操作方法和控制器,其中有多個查找下拉菜單。它是否會在實踐中出現這種情況,還是我只是過分偏執? – computrius

1

可能您在模型之間「共享」是有這樣的數據,所有定義的類。我會用一些諸如去:

public static partial class StaticData 
{ 
    public static List<CustomerType> CustomerTypes = new Lisr<CustomerType> 
    { 
     new CustomerType { Name = "Whatever", Discount = 10, ....... }, 
     new CustomerType { Name = "Another", Discount = 0, ........} 
     // etc 
    } 
} 

請注意這是一個局部類,因此您可以跨文件拆分此/文件夾在你的項目和有:

CustomerTypes.cs 
SupplierTypes.cs 
ProductTypes.cs 

和其他任何爲單獨的文件全部構建到一個共享的StaticData類中,該類最終包含您的所有下拉列表定義以及任何其他非數據庫信息。

那麼,在您看來,您可以使用StaticData.CustomerTypes填充選擇選項。

1

CustomerModel(不視圖模型,因爲沒有視圖模型在MVC)不是Customer的模型。它是在視圖Customer中使用的模型。如果這種觀點需要這種信息,那應該是在這種模式中。

我不清楚這個視圖在你的應用程序中的作用,但它看起來像一些客戶創建表單。只是稱之爲CustomerModel並不能很好地解釋課堂的意圖。您可能需要致電CreateModel,在CustomerController中的Create()方法返回的Create.cshtml中使用。然後,將CustomerType添加到此模型是有意義的:如果您想創建客戶,則需要有CustomerType