Search code examples
asp.net-mvcresx

mvc : I want to load my error message from resource file but i get attribute const error


I want to create a multilingual mvc web site so I have been loading all my messages and labels from resource file and in my validation i want show my message from the resource file but i am getting the following error.

An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type

Solution

  • Attribute parameters are restricted to constant values.

    That is, when applying an attribute to something, the arguments must be constant values such as const primitives (string, int, float, bool, double etc), enums, or type.

    For example:

    ##Legal

    [Required("This field is required.")]
    public string Username { get; set; }
    

    ##Error

    [Required(SomeObject.ErrorMessageStringProperty)]
    public string Username { get; set; }
    

    If the string isn't a const, you cannot compile.

    #Hint

    ValidationAttribute classes have already addressed this issue. Instead of providing an ErrorMessage argument, you can provide an ErrorMessageResourceType and ErrorMessageResourceName. These const values are then used to look up the appropriate error message for the culture.

    e.g.

    ##Legal

    [Required(ErrorMessageResourceType = typeof(Resources.Errors), ErrorMessageResourceName="RequiredError")]
    public string Username { get; set; }
    

    ##Further reading

    How to localize ASP.NET MVC application?

    Multiple languages in an ASP.NET MVC application?

    DisplayName attribute from Resources?

    Best practice for ASP.NET MVC resource files

    ##ASP.NET 5/Core

    For devs coming across this post in the future and are seeking the .NET 5 reference... the following documentation cleared everything up for me.

    Globalization and localization in ASP.NET Core