【发布时间】:2011-08-07 12:53:12
【问题描述】:
借助数据注释,现在可以使用 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 中吗?
【问题讨论】:
标签: asp.net-mvc validation localization business-logic