Data-annotation getting errormessage out database - c#

With asp.net mvc you can use the annotation
[Required (errormessage="This is required")]
How can I create something 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

Related

How do I validate data in C# based on a Struts validation.xml?

I have a validation.xml file from Struts, and am going to implement a server-side validation in .NET based on it. The validation.xml file is accompanied with a validationMessages.properties file. Are there any .NET libraries which are capable of performing a validation based on a Struts validation file?
In case this has never been done I'll have to either create such a class, since the validation file is too long and complex to be implemented as mere C# logic. Which begs the question: How would I even begin?
The end-goal is to be able to populate a C# class with properties for all fields, execute a validation method with that class as a parameter and have it return a list of validation error messages (or no errors in case of success).
I'd be surprised if anything like that existed; it's relatively unusual to move from Java -> .NET.
First, see if there are any custom validators. That code would need to be duplicated.
Then pick apart the different forms (or actions, depending on how they did validation). Put each of those into a C# class (but see below) rather than one giant one. I'm not sure what you mean by "A C# class with properties for all fields"; personally I'd go more granular.
Or just use an existing C# validation package and do a translator from Apache Commons Validation to the C# configuration (or code).
It should be a relatively straight-forward process since the validation config is well-known and documented, and all the code is available.

C# MVC Custom Attributes

I have model based on existing database and I have written metadata class and custom attribute class, Now I want to convert all custom attribute logic into Jquery or Javascript custom function, Please guide me simple or any available free tool for the same.
rcdmk and Scott Selby have provided excellent resources for how to implement the IClientValidatable interface to integrate with jquery unobtrusive validation. As an alternative, if you don't want to maintain javascript versions of your validation logic, you could use the RemoteAttribute class to instruct the unobtrusive validation to perform an ajax request to validate the data (in fact in some cases this would be the only proper way to validate something - such as username availability).
RemoteAttribute Class
How to: Implement Remote Validation in ASP.NET MVC
To this moment, there's not a tool for converting custom validator in c# to custom client side validator in JavaScript [that I know of].
I advice you to look for custom validators already built on the web, like http://foolproof.codeplex.com/. Some of them may have what you need and if you can't find one that suits your requirements, follow some tutorials on how to build your own and, maybe, start your own open source project. Since you needed it, others may need it too.
Some tutorials on how to build your own custom validators may get you where you want:
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
http://www.codeproject.com/Articles/301022/Creating-Custom-Validation-Attribute-in-MVC-3
And this is one of my favorite references:
http://anthonyvscode.com/2011/07/14/mvc-3-requiredif-validator-for-multiple-values/
With all this in hand I'm sure you will succeed in create your own client side validators.
You should definitely look at unobtrusive validation in MVC. It adapts MVC to work with Jquery and Jquery validate plugins using data attributes within HTML markup. Once you add a Custom Validation Attribute you must also inherit and implement IClientValidatable. See the following links for more information.
http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
http://www.codeproject.com/Articles/275056/Custom-Client-Side-Validation-in-ASP-NET-MVC3
I don't know what your requirements are for your validation , but jQuery validate plugin
should handle it. It validates for a lot of common needs automatically (phone number, number, empty text, email) it is also very easy to add custom validation if needed.

How to change models editable atttribute based on a condition

Based on user credentials, I will allow users to edit a field or not on a Razor View.
So I currently have one model which I can do this for the properties I forbid:
[Editable(allowEdit=false)]
public string FirstName {get;set;}
but when I add the attribute whether or not a user has permission to edit it, they won't be able to. I cannot change the fields in Razor View either as we use a very different way of rendering model properties.
Any idea how can I overcome this problem?
You might want to create custom validation attribute and use that, in it you can inject your boolean and check and make it conditional (in C#).
The better option is to use Fluent Validation - its much easier to work with in these cases, when you need conditional validation. Also it will keep your models cleaner.
So if you can - use Fluent validation, if not, just define your own property and control it in your code including all conditions. Examples and links to libraries are here
Here is another option for you - complete library built with aim to easy the work you trying to achieve : http://foolproof.codeplex.com/
Hope this helps

ASP.NET MVC4 Multi-lingual Data Annotations

In a standard application I have the following:
[Required]
[DisplayName("Email Address")]
public string EmailAddress { get; set; }
...this in turn generates a label for this form field automatically in English.
Now, if I need my app to support 5 languages, what is the best approach from a ASP.NET MVC application to handle this?
Scope of application is about 400 - 600 data fields.
UPDATE: I will also require support for updating small sections of text in the application like page names and introductions to each form (small paragraph).
Instead of assigning the actual values to the attribute properties, assign keys for resource strings. Then, you can use a custom ModelMetadataProvider that is aware of the localization context and will provide the appropriate string. To get a better solution, you can make your custom ModelMetadataProvider infer conventions, (which cuts down on the need for verbose attributes).
Phil Haack has a blog article called Model Metadata and Validation Localization using Conventions that explains how this works. There is also a corresponding NuGet package called ModelMetadataExtensions with source code available on github at https://github.com/Haacked/mvc-metadata-conventions .
As a side note, I'd recommend reviewing some of the awesome answers I got on an old question of mine: Effective Strategies for Localization in .NET. They don't specifically address your question, but will be very helpful if you are working on a multilingual .NET app.
I would make custom attribute, like [MyDisplayName("Section", "Key")]
And this would provide translation based on selected language. Also check out database driven resources manager, like http://www.west-wind.com/presentations/wwDbResourceProvider/
The best approach for localization is to store your strings in the database and not resource files unless,
Your app is very static
Your language set is very static
You can decorate your model with custom attribute where you set default string and DB id for the resource e.g.
[MyResource("email", 123)]
You can write custom http delegating handler to get resource out of cache (for example). Once you authenticate client, you know client's language demand and resource id. So, the client with Spanish and resource id = 1 will get "Si", the one with English will get "Yes". The resource id will be mapped to language-specific string.

Dynamically add inputs to view for properties

Unfortunately I'm relatively new to MVC so what I am trying to do might be quite simple or not even possible in MVC.
I have a series of template classes in a library which can have template added, change or removed between versions. What I am trying to do is create a page that will allow for the user to select from a drop down list which template they wish to work on and then once they have selected the template be able to populate the properties of the template through text boxes, drop down lists, date selectors etc.
Whilst I could in theory create a View for each of the different templates, I would like to avoid that as if the templates can be added/changed/removed with newer versions of the library, I would like to avoid having to rewrite the Views each time that happens.
Does anyone have any suggestions on how I might be able to achieve this or know of existing references dicussing this?
If I've missed out any information which would be of use please let me know.
Thanks for any help/advice in advance.
Satal
Without writing the code, what you are looking for is a component that builds html based on what model/object it is passed to satisfy the population of that model via a web browser.
I dare say that this is possible!
An easy or easier route would be:
Decorate the properties within your template models with attributes that would dictate what sort of input control they require.
Also decorate the properties with an attribute that specifies the name of the attribute.
Create a component that accepts a model/type and creates HTML to satisfy the input of that type. Of course this must be rendered within a form.
On postback/submit to your action use the Request["{propertyName}"] to get the value of input fields to populate the properties.
Your controller action will accept the name of the Template so that you know which model to create
System.ComponentModel.DataAnnotations is a good place to start before writing your own custom attributes.

Categories