Localization in ASP.NET MVC 2 using ModelMetadata
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:
-
Download the MVC futures library
-
Add a reference to the Microsoft.Web.MVC.AspNet4 dll.
-
Add a folder in your MVC project where you will store the
resx files
-
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”
-
Confirm that the “Build Action” of the resx is set to
“Embedded Resource”
- Add your localized strings in the resx.
-
Register the new ModelMetadataProvider
protected void Application_Start()
{AreaRegistration.RegisterAllAreas();RegisterRoutes(RouteTable.Routes);//Add thisModelMetadataProviders.Current = new DataAnnotations4ModelMetadataProvider();DataAnnotations4ModelValidatorProvider.RegisterProvider();}
-
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; }
}
- 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!