0

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.

1 Answer 1

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

Check the following link:

Validation of dynamic fields in a MVC

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Carlos , this answers the question partially. I have a more complex object than a List<ClassName> . the custom object I have might contain simple properties( str , int) or it may contain complex object as well e.g : AdditionRuntimeData might have a AdditionRuntimeData.CAR object which has AdditionRuntimeData.CAR.CarMake AdditionRuntimeData.CAR.CarEnginePower property . The CAR child object might have WHEEL obj. I need to have a generic way of being able to assign attributes like REQUIRED or DataType(..Password) to it. Hence need to implemet it as a dynamic object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.