C# 模型和视图模型mvc中的验证
我有一个域模型,其中有10个字段。 我有5个视图,其中包含此模型中的不同字段(每个视图具有不同的字段集)。为此,我为每个视图创建了一个ViewModel(总共5个ViewModels) 我的问题是,在每个视图模型中,我都必须复制验证逻辑。是否有任何简单的方法可以避免每个ViewModel的验证逻辑重复 下面是我的模型和ViewModels的外观C# 模型和视图模型mvc中的验证,c#,asp.net,asp.net-mvc,entity-framework,asp.net-mvc-4,C#,Asp.net,Asp.net Mvc,Entity Framework,Asp.net Mvc 4,我有一个域模型,其中有10个字段。 我有5个视图,其中包含此模型中的不同字段(每个视图具有不同的字段集)。为此,我为每个视图创建了一个ViewModel(总共5个ViewModels) 我的问题是,在每个视图模型中,我都必须复制验证逻辑。是否有任何简单的方法可以避免每个ViewModel的验证逻辑重复 下面是我的模型和ViewModels的外观 public class Student { public int Id { get; set; } [Required] [S
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使用它们,而不必到处提及。是。
让每个ViewModel
继承自BaseModel
,并在那里拥有验证逻辑
您的基本型号
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
您可以尝试验证您的模型将验证放入属性中,然后将它们放在ViewModel的注释中。您可以向我们展示您当前如何验证您的模型的片段吗?您好@DionV。我添加了我目前正在做的代码。你能用一个小例子解释一下吗?@aditya当然,如果你能包含一些有问题的代码片段,我可以提供一个简短的例子public bool validationMethod()的含义是什么?另一种方法?如何验证此方法中的字段?@aditya现在可以看到答案了。以前只是对代码外观的盲目猜测。我现在包括了你的代码。让我们来看看。