使用数据注释,现在可以通过像这样的Resource.resx文件轻松地本地化错误消息,例如:
现在,假设我想检查某个学生是否已经在给定的月份和年份进行了付款:
如果他已经完成了付款,我将在我的服务层执行以下操作:
public class Student
{
. . .
[Required(ErrorMessageResourceName ="Required",
ErrorMessageResourceType = typeof(StudentResources))]
[StringLength(16)]
[Display(Name = "FirstName", ResourceType = typeof(StudentResources))]
public string FirstName { get; set; }
. . .
}
现在,假设我想检查某个学生是否已经在给定的月份和年份进行了付款:
public bool CheckIfAlreadyPaid(Payment payment)
{
return repository.GetPayments().Any(p => p.StudentId == payment.StudentId &&
p.Month == payment.Month &&
p.Year == payment.Year);
}
如果他已经完成了付款,我将在我的服务层执行以下操作:
if (CheckIfAlreadyPaid(payment))
{
modelState.AddModelError("AlreadyPaid",
Resources.Views.Payment.PaymentCreateResources.AlreadyPaid);
}
它可以工作,但我对在服务层中引用资源文件不太自信。
是否有一种标准或更好的方法来本地化与模型属性(数据注释)无关的错误消息 - 来自业务逻辑规则的错误? 我是否仍应将这些错误添加到ModelStateDictionary中?