vendredi 20 novembre 2015

Custom ModelValidatorProvider - get access to containertype property

I have the following class (simplified for question)

MyPageData.cs
{
    string PageName {get;set;}
    List<Field> Fields {get;set;}
}

Which contains a collection of another class (fields for the user to enter).

Field.cs
{
     string Id {get;set;}
     object Value {get;set;}
}

And this is bound to the view in a manner like below

Data.cshtml
{
   @model MyPageData

   @using(Html.BeginForm())
   {
     @foreach(var field in fieldsData)
     {
          var index = MyPage.Fields.IndexOf(field);
          @Html.TextBoxFor(t => t.MyPage.Fields[index].Value);
     }
   }
}

Some of the field values require validation. Having read around a bit, I was hoping to do this with a Custom ModelValidatorProvider, but this only seems to provide me with details of the property that I am trying to bind, and the page object model as a whole (example code below)

public class CustomModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
      protected override IEnumerable GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable attributes)
        {
            if(metadata.PropertyName == "Value" && metadata.ContainerType == typeof(Field))
{
    var id = **Some magic to work out the id of the Field that this value property is set for;**
    once we have the id then we can work out what validators to apply 
}            

            return base.GetValidators(metadata, context, attributes);
        }
}

So the problem that I am having is working out which field this 'Value' property is being set for. The container type shows as Field.cs, but I can't seem to get any values for this - I can get the container values, but this returns the MyPageData.cs with all of the fields, so I can only then match it by value.

Any ideas anyone?

Aucun commentaire:

Enregistrer un commentaire