Data-annotation getting errormessage out database
With asp.net mvc you can use the annotation [Required (errormessage="This is required")]
How can I create somethin开发者_StackOverflow中文版g like this:
[Required (errormessage="ERRORXX")]
So I can look up in a database what this ERRORXX is and display it on my form. Now my form displays ERRORXX.
How can I create something that solves my problem?
Thx!
Just an idea: why not pull the error messages from a resx file? I think this is the common way of doing this. It even allows you to localize your error messages easily.
I think that by using a resource file (resx file) it's even easier to change the error messages later on. A resx file can be opened and edited in Word Pad for example. You don't need to access a database with username/password, query it, etc.
Localizing ASP.NET MVC Validation
Globalizing ASP.NET MVC Client Validation
Take a look here too:
Model Validation & Metadata in ASP.NET MVC 2
Customizing ASP.NET MVC 2 - Metadata and Validation
The default route to take is with Resources. However, I understand your pain :) The way I've achieved it is a little unusual, but I'll give you a quick rundown. In our project, using resource files is not an option as its way too limited for our purposes, the details of which I won't bore you with now! :) At it's most basic principle, we're setting the errorMessage property of the validation attribute to some sort of "key", and then just using that as a way to lookup the correct (languaged) response in our CMS database, when the validation fails (in our case using MVC, when we update the model and check the state - all at Controller level).
This is the same principle as using the resources (by specifying "ErrorMessageResourceName" and "ErrorMessageResourceType"), but you get to do what you want with it.
To be clear, we originally extended the RequiredAttribute (as one example) with our own stuff, including putting in properly named arguments to allow us to retrieve a sensible CMS value from the database later on. To be extra clear, we're using MVC and custom HtmlHelpers to render our own ValidationControls, which are what ultimately consume the custom values from our custom annotations, etc - None of this affects the dumbed-down principle here though, which is to just use "errorMessage" , or something like it, as a way to look up the actual message from where YOU want to, and WHEN you want to.
I think you mean you want to read/use attribute declarations for a given property?
If so, you could either make your own RequiredAttribute class (to allow adding new or more appropriate properties as you wish). See: Attributes Tutorial
精彩评论