4

First, I want to clarify that I'm currently using the ASP.NET MVC's Model entities as ViewModel because my project is based on MVCVM, so I'm not simply confusing the two.

Anyway MVC automatically creates me a few attributes for ViewModel entities like the following (from the wizard, localized in Italian)

public class LoginModel
{
    [Required]
    [Display(Name = "Nome utente")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Memorizza account")]
    public bool RememberMe { get; set; }
}

Replacing the Display attribute with [Display(Name = LoginViewModelResources.lblUsername)] causes compilation error: "Argument must be a constant expression, typeof expression or matrix creation expression". In a few words, a property reference is a no-no.

The Razor view uses tags such as the following for generating HTML

@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)

How can I localize the ViewModel in order to display the correct messages at front-end?

usr-local-ΕΨΗΕΛΩΝ
  • 26,101
  • 30
  • 154
  • 305

1 Answers1

11

Like this:

[Required]
[Display(Name = "lblUsername", ResourceType = typeof(LoginViewModelResources))]
public string UserName { get; set; }

For this to work you must define a LoginViewModelResources.resx file with Custom Tool=PublicResXFileCodeGenerator (you set this in the properties of the resource file) and containing a label lblUsername which will hold the localized resource.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I'm about to try this, but I believe that LoginViewModelResources *can* be stored in a separate assembly – usr-local-ΕΨΗΕΛΩΝ Dec 29 '12 at 17:25
  • It doesn't matter where it's stored. What's important is that you have specified the `PublicResXFileCodeGenerator` generator for it so that Visual Studio generates a class wrapper that is **public**. By default it uses internal modifier and it cannot be accessed. – Darin Dimitrov Dec 29 '12 at 17:30
  • How can you dynamically switch between resource file? Say for example you have France and English version of the resource file, but here in the Display you have hardcoded by saying typof(XXX)....which means always bound to one resource – Dan Hunex Mar 22 '13 at 21:49
  • @DanHunex, you switch by changing the current `CultureInfo`. – Darin Dimitrov Mar 23 '13 at 23:15