2016-02-12 147 views
1

我有一個領域模型,其中有10個領域。 我有5個視圖與此模型中的不同字段(每個視圖有不同的字段集)。爲此,我爲每個視圖創建了一個ViewModel(共5個ViewModel)。驗證模型和視圖模型mvc

我的問題是在每個視圖模型中我必須複製驗證邏輯。有沒有簡單的方法來避免驗證邏輯複製每個ViewModel?

下面是我的模型和ViewModel的樣子。

public class Student { 
    public int Id { get; set; } 
    [Required] 
    [StringLength(50)] 
    public string Name { get; set; } 
    [StringLength(15)] 
    [DataType(DataType.PhoneNumber)] 
    public string Mobile { get; set; } 
    [DataType(DataType.EmailAddress)] 
    public string Email { get; set; } 
    [Range(5,12)] 
    public int ClassId { get; set; } 
    [Range(0,1000)] 
    public int MarksObtained { get; set; } 
    [DataType(DataType.DateTime)] 
    public DateTime DateOfBirth { get; set; } 
} 


public class StudentDetailsViewModel { 
    //validation duplicated for each field 
    public int Id { get; set; } 
    [Required] 
    [StringLength(50)] 
    public string Name { get; set; } 
    [StringLength(15)] 
    [DataType(DataType.PhoneNumber)] 
    public string Mobile { get; set; } 
    [DataType(DataType.EmailAddress)] 
    public string Email { get; set; } 
    [DataType(DataType.DateTime)] 
    public DateTime DateOfBirth { get; set; } 
} 


public class StudentMarksViewModel 
{ 
    //validation duplicated for each field 
    public int Id { get; set; } 
    [Required] 
    [StringLength(50)] 
    public string Name { get; set; } 
    [Range(5, 12)] 
    public int ClassId { get; set; } 
    [Range(0, 1000)] 
    public int MarksObtained { get; set; } 
} 

所以我不希望我的驗證邏輯在任何地方重複。我想要一個集中的驗證邏輯和我的ViewModels來使用它們,而不必提到任何地方。

+0

你可以嘗試驗證你的模型 – FKutsche

+0

把你的驗證屬性,然後將它們放在你的viewmodel的註釋 –

+0

你能告訴我們你目前如何驗證你的模型的片段嗎? –

回答

1

是的。

讓每個ViewModelBaseModel繼承,並在那裏有驗證邏輯。

你的基本型號

public class VM_Student //Your Base 
{ 
    //Only include Attributes here that you need every time. 
    public int Id { get; set; } 
    [Required] 
    [StringLength(50)] 
    public string Name { get; set; } 

} 

你的ViewModels

public class VM_StudentFull : VM_Student 
{ 
    //Only Add the Extra Fields here, the StudentFull inherits 
    //the other attributes and validation 
    [StringLength(15)] 
    [DataType(DataType.PhoneNumber)] 
    public string Mobile { get; set; } 
    [DataType(DataType.EmailAddress)] 
    public string Email { get; set; } 
    [DataType(DataType.DateTime)] 
    public DateTime DateOfBirth { get; set; }   
} 

public class VM_StudentMarks : VM_Student 
{ 
    //Only Add the Extra Fields here again, 
    //the StudentMarks inherits the other attributes and validation 
    [Range(5,12)] 
    public int ClassId { get; set; } 
    [Range(0,1000)] 
    public int MarksObtained { get; set; } 
    [DataType(DataType.DateTime)]   
} 

這僅僅是一個簡單的例子,當然你需要它相應的匹配您的解決方案。 在每個ViewModel中挑出您需要的屬性,並將其明確添加到新的ViewModel

+0

你可以用一個小例子來解釋一下嗎? – aditya

+0

@aditya當然,如果你可以包含一些代碼片段,我可以提供一個簡短的例子 –

+0

我添加了代碼。你能解釋一下嗎? – aditya