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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With