Home » ASP » ASP.MVC » How to localize data attribute in MVC3?

How to localize data attribute in MVC3?

If you are using the Data Annotation with Asp.Net MVC you might need to localize the message from these annotation.

Here is an example:

public class Person
{
    [Required(ErrorMessage="FirstName is required")]
    public string FirstName { get; set; }
    //...
}

If you want to have the Data Annotation translated in many languages, you should use two others properties that are : ErrorMessageResourceType and ErrorMessageResourceName. This will let you specify the resource type and the resouce name which is the key of inside the resource file.

public class Person
{
    [Required(ErrorMessageResourceType=typeof(MyResourcesNameSpace.ResourcesFile), ErrorMessageResourceName="FirstNameRequiredKey")]
    public string FirstName { get; set; }
    //...
}

This way, you will have your application localized from the Model to the View without any problem.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

3 Responses so far.

  1. Patrick says:

    Hi,

    If it’s a date, how do you set the Format to present the database stored value to the correct regional format depending on the country that it’s been displayed?

    Thanks

    • The message will be in the correct regional format because you should have 1 resource file per region. So, if you want a French format “YYYY-mm-dd” when the regional setting is set to French and an English format “mm/dd/yy” than it will be automatically in the YourResourceFile.fr.resx instead of YourResourceFile.en.resx. In both of those file you can specify the message with the correct format.

      • Patrick says:

        So if I understand I need to had an entry in each resource file with a Name like “DateFormat” and a value like “DD-MM-YYYY” for the specific country setting?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.