Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to set Error Message [Attribute] of Data annotation from XML but getting this type of error

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


C#
[Required(ErrorMessage = XMLValidationSingleton.GetErrorMsg("RecordEventManage", "ProgrammeName", "RequiredErrorMsg"))]

[Required(ErrorMessage = RecordEventConstants.ProgrammeID)]
Posted
Comments
Krunal Rohit 16-Nov-15 23:42pm    
If you are trying to use a static string in an attribute for an action inside a Asp.Net MVC’s controller, you will get a strange error.

-KR
Sergey Alexandrovich Kryukov 17-Nov-15 0:03am    
This is totally unrelated to ASP.NET or MVC framework. The compilation error message clearly explains the problem (what's so strange?).
I can explain why .NET attributes impose such limitations, but perhaps it won't be necessary.

The idea of "dynamic" message is pretty much absurd (more exactly, it goes against the .NET metadata technology), but the real problem is to avoid hard-coding of the error message texts. And this problem is easily solved, to certain quite reasonable degree. Please see Solution 1.

—SA
Sergey Alexandrovich Kryukov 17-Nov-15 0:01am    
Which part of error message is unclear? (I mean not your error message, but the error message the compiler gives you. :-)
—SA

1 solution

Instead of string ErrorMessage property of the attribute System.ComponentModel.DataAnnotations.RequiredAttribute, better use one of two other way of getting error string information: use the property ErrorMessageResourceName or ErrorMessageResourceType.

I strongly recommend using ErrorMessageResourceType: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.errormessageresourcetype(v=vs.110).aspx[^].

Here is the thing: resource name is still a string, and a compiler won't be able to validate this string. For a type, a compiler at least validates that this is a valid type. Unfortunately, it can be some unrelated type, which is the usual problem if attributes. Fundamentally, the problem is that .NET reflection is not a fully-fledged system based on meta-types. Explanation of meta-type concepts is too complex and would not be entirely appropriate here: you don't have it with CLR, period.

But with ErrorMessageResourceType you can well use the important feature of .resx-based resource technology: each .resx resource creates an auto-generated file, and the type is prescribed in this type, you just use whatever you have in this auto-generated file.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900