22

I want to get error message from resources. When i tried codes below i take that error:"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type" What can i do ?

public class UserLoginModel
{
     [Required(ErrorMessage =Resources.PageResources.enterYourEmail)]
     public String Email{ get; set; }

     [Required(ErrorMessage =Resources.PageResources.enterPassword)]
     public String Password { get; set; 
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Merve Kaya
  • 235
  • 1
  • 3
  • 5
  • 1
    possible duplicate of [Why can't I use resources as ErrorMessage with DataAnnotations?](http://stackoverflow.com/questions/2688888/why-cant-i-use-resources-as-errormessage-with-dataannotations) – Liam Jul 30 '13 at 08:53

2 Answers2

52

Try this

 [Required(ErrorMessageResourceType = typeof(Resources.Resources),       
            ErrorMessageResourceName = "enterYourEmail")]
 public String Email{ get; set; }

 [Required(ErrorMessageResourceType = typeof(Resources.Resources),       
            ErrorMessageResourceName = "enterPassword")]
 public String Password { get; set; 
Amit
  • 15,217
  • 8
  • 46
  • 68
  • I had to add ErrorMessage = null to make it work with asp.net mvc 5. Like: [Compare("NewPassword", ErrorMessageResourceType = typeof (Resources.ModelStateErrors.Index), ErrorMessageResourceName = "passworddonotmatch", ErrorMessage = null)] public string ConfirmPassword { get; set; } – Ali Baig Oct 09 '16 at 11:42
3

A similar approach but without the problem related by @Ali Baig about to have to add ErrorMessage = null to make it work.

    [Required(ErrorMessageResourceName = nameof(Resources.Global_Errors.ReqName),
 ErrorMessageResourceType = typeof(Resources.Global_Errors))]
AFetter
  • 3,355
  • 6
  • 38
  • 62