Globalisation and Localisation

Ok, so I said I wasn’t going to do a post on globalisation and localisation because there’s so much out there already. However, I thought I’d put together some of my thoughts and examples I’ve found.

I want to show how to use a separate Resources folder to keep all localisation files instead of using the global or local resource folders that Visual Studio can create. This will allow us to access the resources at any time, including for testing.

I’m using the Contoso University project that you can download here.

So, create a folder called ‘Resources’ and add a couple of .resx files under the folder. One is to be called Student.resx and one to be

Next, set the properties on each file to be an Embedded Resource (if not already). Set the ‘Custom Tool’ property to ‘PublicResxFileCodeGenerator’. Set the ‘Custom Tool Namespace’ to be ‘Resources’. This will give us an easy accessor to the resource files. Make sure the project builds at this point.

We can now add some strings to our resx files. Add the following Name Value pairs to the Student.resx file:

and the following pairs to the file

We can now configure the Student model to make use of the resources for our validation. In the Student.cs file under the Models folder, add the following attributes:

        [Display(Name = "StudentName", ResourceType = typeof(Resources.Student))]
        [Required(ErrorMessageResourceType = typeof(Resources.Student), ErrorMessageResourceName = "StudentNameRequired")]
        [StringLength(50, ErrorMessageResourceType = typeof(Resources.Student), ErrorMessageResourceName = "StudentNameTooLong")]
public string LastName { get; set; }

The attributes will set our display name, the error message to show it is required and the maximum length of the field. You should see in Visual Studio that we have the intellisense for the Resources object. Unfortunately, it’s not pretty. Phil Haack has some thoughts on this here. It’s a proof of concept that hasn’t been updated but has some great ideas.


Further reading:

We can also use fluent validation to create validation rules on the model. This does mean the rules are somewhere else than on the model. The rules can get overlooked. Jerrie Pelser has a good article here.


Leave a Reply

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