我想知道解决这个问题的正确方法是什么。我目前有一个模型 - (如下所示),其中包含我的记录所需的所有字段。
我的问题是创建记录时我只需要传递数据 CustomerID,EmployeeID,Date和ArrivalTime。
在稍后更新记录时,将填充模型中的其余字段。
由于我的某些字段是必需的,如果我不发布这些字段的数据,这显然会导致验证错误。
我想知道实现这个目标的最佳做法是什么?
我应该将模型拆分为两个吗?还是可以进行部分验证?
public class CustomerSupportRecord
{
public int CustomerSupportRecordID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Please enter a Date")]
[DataType(DataType.Date)]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Required(ErrorMessage = "Please select an Arrival Time")]
[DataType(DataType.Time)]
[Display(Name = "Arrival")]
public DateTime ArrivalTime { get; set; }
[Required(ErrorMessage = "Please select a Departure Time")]
[DataType(DataType.Time)]
[Display(Name = "Departure")]
public DateTime DepartureTime { get; set; }
[Required(ErrorMessage = "Please select a Type")]
[Display(Name = "Type")]
public int CustomerSupportTypeID { get; set; }
[Display(Name = "Setting")]
public string ReflectionSetting { get; set; }
[Display(Name = "Advisor")]
public string ReflectionAdvisor { get; set; }
[Display(Name = "Notes")]
public string Notes { get; set; }
[Display(Name = "Comments")]
public string Comments { get; set; }
// Navigation Properties
public virtual Customer Customer { get; set; }
public virtual CustomerSupportType CustomerSupportType { get; set; }
public virtual Employee Employee { get; set; }
}
答案 0 :(得分:1)
正确的方法是为不同的视图使用不同的viewmodel类,并且只包含该视图所需的属性。
所以第一个视图的viewmodel看起来就像这样:
public class CustomerSupportRecordForCreation
{
public int CustomerSupportRecordID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Please enter a Date")]
[DataType(DataType.Date)]
[Display(Name = "Date")]
public DateTime Date { get; set; }
[Required(ErrorMessage = "Please select an Arrival Time")]
[DataType(DataType.Time)]
[Display(Name = "Arrival")]
public DateTime ArrivalTime { get; set; }
}
您必须在viewmodel类和域/ dal类之间进行映射。这就是像AutoMapper这样的工具派上用场的地方。
修改自动播放器:
使用Automapper非常简单。
您必须配置映射(即在Application_Start
中)。当您要映射的类的属性以相同的名称命名时,其简单如下:
Mapper.CreateMap<CustomerSupportRecord,
CustomerSupportRecordForCreation>();
然后您可以在应用中使用映射。如果您有CustomerSupportRecord
并想要为您的观点返回CustomerSupportRecordForCreation
,请写:
CustomerSupportRecord record = getRecordFromDb...
return View(Mapper.Map<CustomerSupportRecordForCreation>(record));
CodeProject上有一篇很好的教程文章:http://www.codeproject.com/Articles/61629/AutoMapper或google