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

标签 asp.net-mvc validation localization business-logic

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

相关文章:

Android checkLocationSettings 从未在 onResume 中调用

c# - MVC - 在 ViewModel 中进行验证就足够了吗?

angularjs - 在ui-grid中显示数据的一些问题

iOS8 区域本地化(例如 pt-BR)?

asp.net-mvc - MVC 验证器错误随着时间控制被赋予 Controller 而消失

c# - 在 ASP.NET MVC (3) 中使用数据注释验证时是否可以生成属性的计算值?

jquery表单验证具有相同id和名称的多个复选框

c# - ASP.NET MVC、RavenDb 和单元测试

asp.net-mvc - ADFS-ID1059 : Cannot authenticate the user because the URL scheme is not https and requireSsl is set to true

javascript - 如何在 Javascript 中调用 @using (Html.BeginForm())