Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get another property's value from ModelMetaData

I'm trying to get to another property's value from within the GetClientValidationRules method of a custom validation attribute.

Here is my attempt (based on Darin's response on another question):

public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
    ModelMetadata metadata, ControllerContext context)
{
    var parentType = metadata.ContainerType;
    var parentMetaData = ModelMetadataProviders.Current
        .GetMetadataForType(null, parentType);

    var parentMetaData = ModelMetadataProviders.Current
        .GetMetadataForProperties(context.Controller.ViewData.Model, parentType); 

    var otherProperty = parentMetaData.FirstOrDefault(p => 
        p.PropertyName == "SomeProperty");

    var otherValue = otherProperty.Model;

    var rule = new ModelClientValidationRule
    {
        ValidationType = "customvalidatorattribute",
        ErrorMessage = this.FormatErrorMessage(metadata.GetDisplayName()),
    };

    yield return rule;
}

However, when trying to set otherValue, I get:

System.Reflection.TargetException: Object does not match target type.

like image 403
Jerad Rose Avatar asked Nov 04 '11 19:11

Jerad Rose


2 Answers

The problem is that you are not passing in the bound model. Change the following two lines:

var parentMetaData = ModelMetadataProviders.Current
    .GetMetadataForProperties(context.Controller.ViewData.Model, parentType); 
var otherValue = (string)parentMetaData.FirstOrDefault(p => 
    p.PropertyName == "SomeProperty").Model;

This will get the full metadata (including the bound values) from the current model.

like image 73
counsellorben Avatar answered Oct 10 '22 01:10

counsellorben


@JeradRose, the problem with your TargetException is because of this line:

var parentMetaData = ModelMetadataProviders.Current
    .GetMetadataForProperties(context.Controller.ViewData.Model, parentType);

parentType needs to be context.Controller.ViewData.Model.GetType().

Probably you already fixed it, but I just got it today.

like image 42
Fabio Milheiro Avatar answered Oct 10 '22 02:10

Fabio Milheiro