2016-01-07 38 views
1

我對ASP MVC相當陌生,所以當我第一次創建一個頁面時,我製作了一個ViewModel,它具有扁平化與地址和聯繫信息相關的屬性。這些屬性非常常見,我可以看到它們被重用。所以我們可以說我有以下視圖模型:重複使用ViewModels和數據註解

public class InformationViewModel { 
    [Required(ErrorMessage = "Name is required")] 
    public string Name { get; set; } 
    public string Phone { get; set; } 
    public string EMail { get; set; } 
    public Uri WebSiteURL { get; set; } 
    public Uri FacebookURL { get; set; } 

    [HiddenInput(DisplayValue = false)] 
    public string AddressId { get; set; } 
    public string AttentionLine { get; set; } 
    public string CareOf { get; set; } 
    public string CountryCode { get; set; } 
    public string CountryName { get; set; } 
    public string Address1 { get; set; } 
    public string Address2 { get; set; } 
    public string City { get; set; } 
    public Dictionary<string, string> Countries { get; set; } 
    public Dictionary<string, string> States { get; set; } 
    public string StateCode { get; set; } 
    public string StateName { get; set; } 
    public string PostalCode { get; set; } 

    //Some other properties specific to the view here 
} 

前兩個屬性塊是跨多個視圖模型重用。現在我正在研究一個需要這些相同屬性的新頁面。

1)我會將它們分離出它們自己的View Model(或Model?)文件(例如AddressViewModel/ContactViewModel)嗎? 1a)如果我將它們分開並通過將它們作爲屬性包含在InformationViewModel中來重複使用它,那麼可以使用以下代碼行:public AddressViewModel addressViewModel {get; set;}

2)我將如何刪除或包含的視圖模型應用數據的註釋(如public AddressViewModel addressViewModel {get; set;}?例如,如果我想需要名稱上的一些意見,但不是爲別人。

回答

2

查看模型是針對意見。因此,它是創建視圖特定的平面視圖模型是個好主意,但如果你有一個以上的視圖模型一些共同的屬性,你可以根據需要從基礎視圖模型繼承。

public class CreateUser 
{ 
    [Required] 
    public string Name {set;get;} 
    [Required] 
    public string Email {set;get;} 

    public virtual string City { set; get; } 
} 
public class CreateUserWithAddress : CreateUser 
{ 
    [Required] 
    public string AddressLine1 {set;get;} 
    public string AddressLine12 {set;get;} 

    [Required] 
    public override string City { set; get; } // make city required 
} 

inhering當從基本視圖模型中,您應該能夠覆蓋基類的屬性並將數據註釋添加到您的子類中s(就像我們用City屬性所做的那樣)。但是,您不能刪除派生類中基類中定義的數據註釋。

+0

如果您使用接口,而您的VM可以實現許多「基本」類型,例如'CreateUserWithAddress:ICreateUser,ICreateAddress'。 – Jasen