Member Expression cannot convert to object from nullable decimal

别来无恙 提交于 2019-12-05 12:50:57

The problem is that you can't just use object as TProperty when calling TextBoxFor<TModel, TProperty>(). It expects a lambda expression of the form Func<TModel, TProperty>, and the variance rules of C# are such that a Func<TModel, decimal?> is not assignment compatible with Func<TModel, object>. You also can't simply use Convert(), because the MVC internals won't accept a lambda whose body is a Convert expression.

What you can do is use dynamic binding to invoke TextBoxFor<TModel, TProperty>() with the correct type arguments:

public Expression GetParameterByName(PropertyInfo pi)
{
    var fieldName = Expression.Parameter(typeof(RuleViewModel<T>), "x");
    var fieldExpression = Expression.PropertyOrField(
        Expression.Property(fieldName, "RuleModel"),
        pi.Name);
    var exp = Expression.Lambda(
        typeof(Func<,>).MakeGenericType(typeof(RuleViewModel<T>), fieldExpression.Type),
        fieldExpression,
        fieldName);
    return exp;
}

// ...

@InputExtensions.TextBoxFor(Html, (dynamic)Model.GetParameterByName(prop))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!