Home >Backend Development >C++ >How Can I Dynamically Retrieve Display Names from Resource Files in .NET?

How Can I Dynamically Retrieve Display Names from Resource Files in .NET?

DDD
DDDOriginal
2025-01-01 14:28:10256browse

How Can I Dynamically Retrieve Display Names from Resource Files in .NET?

Retrieving Display Names from Resources

In localized applications, developers often encounter the need to display user-friendly labels for model properties. While the DisplayName attribute allows for the specification of static display names, there may be scenarios where these names need to be dynamically retrieved from external sources, such as resource files.

Unfortunately, using the DisplayName attribute alone does not provide the ability to specify a dynamic value from a resource. The compiler error encountered, "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type," indicates that the provided argument must be a static value.

Workaround with .NET 4 and MVC 3

For applications utilizing MVC 3 and .NET 4, a solution exists through the use of the updated Display attribute found in the System.ComponentModel.DataAnnotations namespace. This attribute extends the functionality of its predecessor, including the ability to leverage localization.

To utilize this attribute, modify your model as follows:

public class MyModel
{
    [Required]
    [Display(Name = "labelForName", ResourceType = typeof(Resources.Resources))]
    public string name { get; set; }
}

Note: This workaround requires that the resource file is marked as an 'Embedded resource' and uses the 'ResXFileCodeGenerator' custom tool. Additionally, App_GlobalResources or App_LocalResources should not be used with MVC.

The above is the detailed content of How Can I Dynamically Retrieve Display Names from Resource Files 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