0

When using MVC Foolproof Validation, is it possible to have a custom validation asynchronous? I am wanting to retrieve an object from a DbSet in a custom validation, to check if the object exists.

Is this possible? If not, is there a work around that achieves the same result?

Here is my code:

public class RequiredThumbnailAssetId : ModelAwareValidationAttribute
{
    static RequiredThumbnailAssetId() { Register.Attribute(typeof(RequiredThumbnailAssetId)); }
    public async override Task<bool> IsValid(object value, object container)
    {
        var model = (IGridViewItemWithAssetId)container;
        if (model.thumbnailAssetId <= 0)
        {
            return false;
        }
        CanFindLocationDatabaseContext db = new CanFindLocationDatabaseContext();
        Asset asset = await db.assets.FindAsync(model.thumbnailAssetId);
        if (asset == null)
        {
            return false;
        }
        return true;
    }
}

Here is the error that I am getting:

'CanFindLocation.CustomValidations.RequiredThumbnailAssetId.IsValid(object, object)': return type must be 'bool' to match overridden member 'Foolproof.ModelAwareValidationAttribute.IsValid(object, object)'

Thanks in advance.

Simon
  • 7,991
  • 21
  • 83
  • 163

1 Answers1

0

You could use the classes defined in the post How would I run an async Task<T> method synchronously? and then separate the override you need and the async call out into separate methods. This would allow you to call the synchronous override from the async request.

public class RequiredThumbnailAssetId : ModelAwareValidationAttribute
{
    static RequiredThumbnailAssetId() { Register.Attribute(typeof(RequiredThumbnailAssetId)); }

    public async override Task<bool> CheckValid(object value, object container)
    {
        var valid = AsyncHelpers.RunSync<bool>(() => isValid(value,container));
        return valid;
    }

    public override bool IsValid(object value, object container)
    {
        var model = (IGridViewItemWithAssetId)container;
        if (model.thumbnailAssetId <= 0)
        {
            return false;
        }
        CanFindLocationDatabaseContext db = new CanFindLocationDatabaseContext();

        Asset asset = await db.assets.FindAsync(model.thumbnailAssetId);

        if (asset == null)
        {
            return false;
        }
        return true;
    }
Community
  • 1
  • 1
Code Uniquely
  • 6,356
  • 4
  • 30
  • 40