Localization in ASP.NET MVC 2 using ModelMetadata

Posted by rajbk on ASP.net Weblogs See other posts from ASP.net Weblogs or by rajbk
Published on Tue, 27 Apr 2010 16:02:12 GMT Indexed on 2010/04/27 16:03 UTC
Read the original article Hit count: 962

Filed under:
|
|
|

This post uses an MVC 2 RTM application inside VS 2010 that is targeting the .NET Framework 4.

.NET 4 DataAnnotations comes with a new Display attribute that has several properties including specifying the value that is used for display in the UI and a ResourceType. Unfortunately, this attribute is new and is not supported in MVC 2 RTM.

The good news is it will be supported and is currently available in the MVC Futures release.

The steps to get this working are shown below:

  1. Download the MVC futures library
     
  2. Add a reference to the Microsoft.Web.MVC.AspNet4 dll.
     
  3. Add a folder in your MVC project where you will store the resx files
    image
     
  4. Open the resx file and change “Access Modifier” to “Public”. This allows the resources to accessible from other assemblies. Internaly, it changes the “Custom Tool” used to generate the code behind from  ResXFileCodeGenerator to “PublicResXFileCodeGenerator”

     image 
  5. Add your localized strings in the resx.
     
  6. Register the new ModelMetadataProvider
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
     
        RegisterRoutes(RouteTable.Routes);
     
        //Add this
        ModelMetadataProviders.Current = new DataAnnotations4ModelMetadataProvider();
        DataAnnotations4ModelValidatorProvider.RegisterProvider();
    }

     
  7. Use the Display attribute in your Model
    public class Employee
    {
        [Display(Name="ID")]
        public int ID { get; set; }
     
        [Display(ResourceType = typeof(Common), Name="Name")]
        public string Name { get; set; }
    }

  8. Use the new HTML UI Helpers in your strongly typed view:
      <%: Html.EditorForModel() %>
      <%: Html.EditorFor(m => m) %>
      <%: Html.LabelFor(m => m.Name) %>

      ..and you are good to go.

    Adventure is out there!

    © ASP.net Weblogs or respective owner

    Related posts about .NET

    Related posts about ASP.NET