Tobias
Tobias

Reputation: 883

MVC 3 validate dynamic form fields. ASP.NET

I'm working on a very dynamic site build at the moment. What I'm trying to do is creating something like a survey that can be created dynamically from a control panel.
In the control panel you add input fields (these are saved in a database), what the user then see is a form that I generate from the database. So if I add 3 input fields to the database the survey will contain 3 fields. If I add 20 fields the survey will have 20 fields.

Now my problem is that I want to validate these fields, and I would like to be able to hook me in with the standard validation flow. I can't create a Model with validation rules since the number of fields and their names are dynamic the only thing I know is what kind of data that is expected in every field (this rule is found in the database).
In an ordinary case I would get the automatic highlighted fields that are not valid and so on thanks to the built in validation flow with ValidationResult and so on.

So the question now is can I somehow simulate parts of the validation and then hook me back in with the validation result, and if not valid, the form prints the error messages and fill the fields with the data that was given?

Regards Tobias

Upvotes: 0

Views: 3538

Answers (1)

Linkgoron
Linkgoron

Reputation: 4870

What I would do is create some kind of expando model, my own ModelMetadataProvider and might also need my own ModelValidator for that model.

Then, you can easily create validation using the Html.EditorFor and other Html helpers, as they use the metadata to create validation.

BTW, you might also need to create a model binder :)

meta data: http://mgolchin.net/posts/21/dive-deep-into-mvc-modelmetadata-and-modelmetadataprovider

http://weblogs.asp.net/seanmcalinden/archive/2010/06/11/custom-asp-net-mvc-2-modelmetadataprovider-for-using-custom-view-model-attributes.aspx

http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html

validator: http://dotnetslackers.com/articles/aspnet/Customizing-ASP-NET-MVC-2-Metadata-and-Validation.aspx#s2-validation

http://dotnetslackers.com/articles/aspnet/Experience-ASP-NET-MVC-3-Beta-the-New-Dependency-Injection-Support-Part2.aspx#s10-new-support-for-validator-provider

model binder:

http://www.singingeels.com/Articles/Model_Binders_in_ASPNET_MVC.aspx

This might bo overkill... But these are the extensibility points that you can use.

Upvotes: 3

Related Questions