views:

581

answers:

3

Hello everyone,

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

A: 

Sounds like overkill (if I understand correctly) - that is creating models on the fly. You are not using the main benefit of having models; compile time checks.

I'd try to use objects specific to the task (for example a UserForm class which would have List of UserFormFields classes and so on) in hand and not create them on the fly.

Edit: What I am suggesting is to not use attribute based validation and design your model with validation in mind. A design like below might explain my point better:

interface IUserValidation
{
    bool IsValid();
}

class RequiredUserValidation : IUserValidation
{
    public bool IsValid()
    {
        // ....
    }
}

class UserFormField
{
    List<IUserValidation> _validations;

    public IEnumerable<ValidationResult> Validate()
    {
       // ...
    }
}
Maxwell Troy Milton King
This is almost how my model looks like. A collection of fields containing data. The problem is that I don't have any information about these fields at compile time. I need to query the database and obtain info from the fields and them populate their attributes
Felipe Lima
A: 

Seems like you would need a custom view model binder that applies validation dynamically.

ongle
+1  A: 

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.

Eilon
Thanks a lot man!
Felipe Lima

related questions