Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2 Data annotations in a dynamically generated model

I am creating an asp.net mvc 2 application generating my view model dynamically depending on user input. Simply put, the user is able to choose which fields he wants to see in his View.

Since the templated helpers rely heavily on model properties and attributes (data annotations), I would need to somehow add the attributes to the view model during runtime. No need to say that this is not a simple task.

So, what do you guys recommend me to do in this scenario? I'm not able to add the attributes statically, so should I go ahead and try to add them dynamically even if it is a lot of work or should I try to use a different approach?

Thanks in advance!

Felipe

like image 333
Felipe Lima Avatar asked Feb 13 '10 02:02

Felipe Lima


1 Answers

A custom model binder would only help you in the binding part. It won't help with the templated helpers or other features of ASP.NET MVC.

I recommend writing a custom metadata provider instead by inheriting from ModelMetadataProvider and registering your provider in global.asax by using ModelMetadataProviders. A custom metadata provider can get its metadata from anywhere it wants: CLR attributes, XML file, database, or a random number generator. The built-in Data Annotations provider of course uses CLR attributes.

You might want to take a look at the source code for the built-in Data Annotations metadata provider to see an example of how to implement a provider. You can download the ASP.NET MVC 2 RC 2 source code from the CodePlex site. There might also be an implementation in the MVC Futures project, but I'm not sure.

like image 171
Eilon Avatar answered Sep 19 '22 17:09

Eilon