gpt4 book ai didi

asp.net-mvc - 使用 ASP.NET MVC 3 本地化非数据注释错误的最佳方法是什么?

转载 作者:行者123 更新时间:2023-12-03 17:59:03 25 4
gpt4 key购买 nike

使用数据注释,现在可以很容易地使用 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 中吗?

最佳答案

我同意,我认为这不应该在服务层。看起来它既可以放入自定义数据验证属性中,也可以在该级别使用其他方法处理(使用 Fluent Validation 可能是一个不错的选择)。无论哪种方式,我认为只要验证保留在 MVC 应用程序本身中,您就可以轻松地使用资源文件来存储消息。

关于asp.net-mvc - 使用 ASP.NET MVC 3 本地化非数据注释错误的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5697487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com