Home >Backend Development >C++ >How Can I Localize DisplayName Attribute Values in .NET?

How Can I Localize DisplayName Attribute Values in .NET?

Barbara Streisand
Barbara StreisandOriginal
2025-01-02 19:52:39400browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn