2016-02-12 205 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