简体   繁体   中英

How to use DataAnnotations ErrorMessageResourceName with custom Resource Solution

I'm building a MVC web application with C#. Since the site will be multilingual, I've implemented my own ResourceManager. This class is responsible for fetching the required resource strings from a database/cache depending on the currents thread culture and works fine so far.

My problem is, I'd like to use the my custom ResourceManager solution to fetch validation error messages when for example using the Required Attribute on a property. Can this be done?

The RequiredAttribute allows to use a custom resource manager :

[Required(
    ErrorMessageResourceType = typeof(CustomResourceManager), 
    ErrorMessageResourceName = "ResourceKey")]
public string Username { get; set; }

UPDATE:

Another possibility is to write your custom attribute:

public class CustomRequiredAttribute : RequiredAttribute
{
    public override string FormatErrorMessage(string name)
    {
        return YourCustomResourceManager.GetResource(name);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM