借助数据注释,现在可以轻松使用 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 中吗?
我同意,我认为这不应该在服务层。看起来它可以放入自定义数据验证属性中,或者使用该级别的其他方法进行处理(使用流畅的验证 http://fluentvalidation.codeplex.com/可能是一个不错的选择)。无论哪种方式,我认为只要验证保留在 MVC 应用程序本身中,您就可以轻松地使用资源文件来存储消息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)