加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 07:39:20 所属栏目:asp.Net 来源:网络整理
导读:使用Data Annotations,现在可以使用Resource.resx文件轻松本地化错误消息,例如: public class Student{ . . . [Required(ErrorMessageResourceName ="Required",ErrorMessageResourceType = typeof(StudentResources))] [StringLength(16)] [Display(Name =
使用Data Annotations,现在可以使用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应用程序本身,您就可以使用资源文件来存储消息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读