Example #1
0
    private static Func <ValueProviderResult, ModelBindingContext, object?> CreateTryParseOperation(Type modelType)
    {
        modelType = Nullable.GetUnderlyingType(modelType) ?? modelType;
        var tryParseMethodExpession = ModelMetadata.FindTryParseMethod(modelType)
                                      ?? throw new InvalidOperationException(Resources.FormatTryParseModelBinder_InvalidType(modelType, nameof(TryParseModelBinder)));

        // var tempSourceString = valueProviderResult.FirstValue;
        // object model = null;
        // if ([modeltype].TryParse(tempSourceString, [valueProviderResult.Culture,] out [modelType] parsedValue))
        // {
        //     model = (object)parsedValue;
        //     bindingContext.Result = ModelBindingResult.Success(model);
        // }
        // else
        // {
        //     AddModelError(bindingContext, new FormatException());
        // }
        // return model;

        var parsedValue = Expression.Variable(modelType, "parsedValue");
        var modelValue  = Expression.Variable(typeof(object), "model");

        var expression = Expression.Block(
            new[] { parsedValue, modelValue, ParameterBindingMethodCache.TempSourceStringExpr },
            Expression.Assign(ParameterBindingMethodCache.TempSourceStringExpr, ValueExpression),
            Expression.IfThenElse(tryParseMethodExpession(parsedValue, CultureExpression),
                                  Expression.Block(
                                      Expression.Assign(modelValue, Expression.Convert(parsedValue, modelValue.Type)),
                                      Expression.Assign(BindingResultExpression, Expression.Call(SuccessBindingResultMethod, modelValue))),
                                  Expression.Call(AddModelErrorMethod, BindingContextExpression, Expression.Constant(new FormatException()))),
            modelValue);

        return(Expression.Lambda <Func <ValueProviderResult, ModelBindingContext, object?> >(expression, new[] { ValueProviderResultExpression, BindingContextExpression }).Compile());
    }