views:

67

answers:

1

if I decorate the properties of my ViewModels with attributes like this:

public class Vm
{

[Required]
[StringLength(35)]
public string Name {get;set;}

}

I am going to get english validation messages:

"this field is required"
"The field Name must be a string with a maximum length of 35"

how could I translate them ?

+2  A: 

You could use the ErrorMessageResourceName property:

[Required(ErrorMessageResourceName = "SomeResource")]
[StringLength(30, ErrorMessageResourceName = "SomeOtherResource")]
public string Name { get; set; }

You may checkout this blog post for an example.


UPDATE:

In Application_Start:

DefaultModelBinder.ResourceClassKey = "Messages";

And in the Messages.resx file you need to add the custom error messages. Use Reflector to look at the System.Web.Mvc and System.ComponentModel.DataAnnotations assemblies in order to see the key names to use.

Darin Dimitrov
I would like to change the default messages without specifying it for each property, I saw once that you have to have a Messages.resx in your App_GlobalResources, but I don't know the keys for each message
Omu
Please see my update.
Darin Dimitrov
@Darin Dimitrov could you please tell me more exactly where in System.Web.Mvc to look
Omu
Oh I see. You are trying to localize the default error messages. I afraid this is not possible unless you install a localized version of the .NET framework. I would recommend you specifying the error message in each attribute and have a custom resources file handling those messages.
Darin Dimitrov
@Darin Dimitrov no, your update was what I needed, I want to localize the validation messages, you showed me once one key PropertyValueInvalid, all I need to know now is where in System.Web.Mvc to find all these keys
Omu
@Omu, what I showed you works only for some special things that are handled by ASP.NET MVC and not DataAnnotations like PropertyValueInvalid which is used for example when trying to bind a string to an integer value which is not of the correct format. You cannot do this with other messages like Required because they are handled by the DataAnnotations framework.
Darin Dimitrov
@Darin Dimitrov this is what you showed me that time: http://stackoverflow.com/questions/3156488/localize-default-model-validation-in-mvc-2 and it works, I thought that there could be some more keys in there to use for translation
Omu