Search code examples
c#asp.net-mvcasp.net-mvc-5globalization

Global Resources in ASP.Net MVC Model ErrorMessage Attribute


I am creating web application in ASP.Net MVC 5.

I need to add user defined languages. (So, it can work in any language).

I have added English text/messages in resources file.

While, for other languages , resources will be generated run time in App_GlobalResources folder.

With this custom resources, I can able to show labels (, buttons etc.) as per selected language.

But, I have issue with ErrorMessage , which is given as attribute in properties of model.

Model classes are in class library, and reference of class library project is added in MVC.

So, can't access resources from App_GlobalResources folder.

And, if I add resources under Project of model class, I can give customize message with following code.

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

But, with this code, I can't use App_GlobalResources.

What will be solution in this scenario?


Solution

  • Finally, I got solution:

    Created custom attribute class.

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

    Custom Attribute class is inheriting CompareAttribute class.

    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));
        }
    
    }
    

    In overridden FormatErrorMessage method, I have put code to get customized error message from Global Resources.