关于c#:ASP.Net MVC模型中的全局资源ErrorMessage属性

Global Resources in ASP.Net MVC Model ErrorMessage Attribute

我正在ASP.Net MVC 5中创建Web应用程序。

我需要添加用户定义的语言。 (因此,它可以使用任何语言工作。)

我在资源文件中添加了英文文本/消息。

对于其他语言,资源将在App_GlobalResources文件夹中生成运行时。

使用此自定义资源,我可以按照所选语言显示标签(,按钮等)。

但是,我有ErrorMessage问题,它是在模型属性中作为属性给出的。

模型类在类库中,并且在MVC中添加了类库项目的引用。

因此,无法访问App_GlobalResources文件夹中的资源。

而且,如果我在模型类的Project下添加资源,则可以使用以下代码给出自定义消息。

1
2
3
    [Required(ErrorMessage ="*")]
    [System.Web.Mvc.Compare("Password", ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName ="PasswordCompare")]
    public string ConfirmPassword { get; set; }

但是,使用此代码,我无法使用App_GlobalResources。

在这种情况下什么是解决方案?


最后,我得到了解决方案:

创建的自定义属性类。

1
2
3
    [Required(ErrorMessage ="*")]
    [CompareCustomAttribute("Password", ClassKey ="Resources", ResourceKey ="PasswordCompare")]
    public string ConfirmPassword { get; set; }

自定义属性类继承了CompareAttribute类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public sealed class CompareCustomAttribute : System.Web.Mvc.CompareAttribute
{
    public CompareCustomAttribute(string otherProperty)
        : base(otherProperty)
    {
    }

    public string ResourceKey { get; set; }

    public string ClassKey { get; set; }

    public override string FormatErrorMessage(string name)
    {
        return Convert.ToString(HttpContext.GetGlobalResourceObject(this.ClassKey, this.ResourceKey));
    }

}

在重写的FormatErrorMessage方法中,我放置了从全局资源中获取自定义错误消息的代码。