Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use DataAnnotations ErrorMessageResourceName with custom Resource Solution

Tags:

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?

like image 647
Mats Avatar asked Feb 27 '10 14:02

Mats


People also ask

What is the use of using system ComponentModel DataAnnotations?

Data annotations (available as part of the System. ComponentModel. DataAnnotations namespace) are attributes that can be applied to classes or class members to specify the relationship between classes, describe how the data is to be displayed in the UI, and specify validation rules.

What are DataAnnotations in net core?

"Data Annotation provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls." Why would I use Data Annotation? There are 3 main areas where you may use it; two of them are related to your data presentation to your end user and one is to design your database.


1 Answers

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);     } } 
like image 125
Darin Dimitrov Avatar answered Oct 19 '22 13:10

Darin Dimitrov