Question

Edit 1:

I have done some research and would like to simplify the question :

I would like to have a model with a dynamic object.

public dynamic AdditionRuntimeData;

this object will be populated at runtime using a database table. I want to decorate this object as well as property inside this object with DataAnnotations like Required , Range etc at runtime.

It looks like the way to go ahead is to implement ICustomTypeDescriptor however even after the implementation , MVC doesnt like the dynamic object in my model and will not even request metadata for it using the DataAnnotationsModelMetadataProvider.CreateMetadata() method.

Is there a way to get around this problem ?

class Absence
{
    [Required()]
    public Guid EmpID { get; set; }

    [Required(ErrorMessage = "Start date is  manadatory")]
    [DataType(DataType.Date)]
    [DisplayName("Absence Start Date")]
    public DateTime AbsenceStart { get; set; }

    [Required(ErrorMessage = "End date is  manadatory")]
    [DataType(DataType.Date)]
    [DisplayName("Absence End Date")]
    public DateTime AbsenceEnd { get; set; }


    //Populate this using a helper class which reads from DB and creates a object tree at runtime.
    public dynamic AdditionRuntimeData;

}

Note : AdditionRuntimeData could be a object which has child objects or it could just be a simple property with value.

The answer given does not allow such depth.

Was it helpful?

Solution

ModelState.AddModelError("Fields[x].SomeProperty", "The Error Message you want to show.);

Check the following link:

Validation of dynamic fields in a MVC

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top