Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling Data Annotation Validation with Custom ValidationResult
    primarykey
    data
    text
    <p>I have a custom ValidationAttribute like this :</p> <pre> <code> public class ReceiverRegion : ValidationAttribute { private RegionService regionService; private CityService cityService; public ReceiverRegion() : base("Incorrect region code") { this.regionService = new RegionService(); this.cityService = new CityService(); } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { int regionId = Convert.ToInt32(value); int plate = Convert.ToInt32((validationContext.ObjectInstance as CorporateOrderItem).ReceiverCity); int productGroupId = Convert.ToInt32(validationContext.Items["productGroup"].ToString()); if (!CheckReceiverRegionExistence(regionId, plate, productGroupId)) { IEnumerable regions = this.regionService.GetList(cityService.GetByPlate(plate).PKCityId); return new CorporateOrderValidationResult(base.ErrorMessage, regions.Select(r=>r.Name)); } return <b>CorporateOrderValidationResult.Success</b>; } private bool CheckReceiverRegionExistence(int plate, int regionId, int productGroup) { return !(regionService.GetByCityAndRegionIdForProductGroup(plate, regionId, productGroup) == null); } } </code> </pre> <p>But as you can see in IsValid method, I'm trying to return a custom object which inherits from ValidationResult. My problem is, I can't access the extra members of my <code>CorporateOrderValidationResult</code> instance since IsValid returns the base ValidationResult type. Below is the code where I call validate and get a collection of ValidationResult as return value. </p> <p><pre><code> List results = new List(); bool isValid = Validator.TryValidateObject(instance, context, results, true); </pre></code></p> <p>I tried to cast results object to <code>List&lt;CorporateOrderValidationResult&gt;</code>, but no matter what I try(for instance --> <code>item as CorporateOrderValidationResult</code> or <code>results.OfType&lt;CorporateOrderValidationResult&gt;()</code> or <code>(CorporateOrderValidationResult)item)</code> I either get InvalidCastException or null value. Is there a possible way to convert this list of result to a list of my custom result class? Thanks...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload