0

使用时MVC Foolproof Validation,是否可以进行自定义验证asynchronous?我想从DbSet自定义验证中检索一个对象,以检查该对象是否存在。

这可能吗?如果没有,是否有解决方法可以达到相同的结果?

这是我的代码:

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;
    }
}

这是我得到的错误:

'CanFindLocation.CustomValidations.RequiredThumbnailAssetId.IsValid(object, object)':返回类型必须是 'bool' 以匹配被覆盖的成员 'Foolproof.ModelAwareValidationAttribute.IsValid(object, object)'

提前致谢。

4

1 回答 1

0

您可以使用文章中定义的类我将如何同步运行异步 Task<T> 方法?然后将您需要的覆盖和异步调用分离到单独的方法中。这将允许您从异步请求中调用同步覆盖。

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;
    }
于 2014-11-10T04:42:37.877 回答