Home >Backend Development >C++ >How Can I Localize DisplayName Attribute Values in .NET?
Localizing DisplayName Attribute Values with Resources
In localized .NET applications, it can be desirable to set the DisplayName attribute of model properties using localized resources. However, attempts to directly use resources within the DisplayName attribute, as shown in the code below, result in compilation errors:
public class MyModel { [Required] [DisplayName(Resources.Resources.labelForName)] public string name{ get; set; } }
To address this limitation, MVC 3 and .NET 4 introduced the Display attribute in the System.ComponentModel.DataAnnotations namespace. This attribute offers enhanced functionality, including localization support. Here's how to utilize it for localized DisplayName values:
public class MyModel { [Required] [Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))] public string name{ get; set; } }
Note that this approach requires your resource file to be set as an "Embedded resource" and use the "ResXFileCodeGenerator" custom tool. Avoid using App_GlobalResources or App_LocalResources with MVC due to limitations with their custom tools.
The above is the detailed content of How Can I Localize DisplayName Attribute Values in .NET?. For more information, please follow other related articles on the PHP Chinese website!