Anelook
Anelook

Reputation: 1277

How to create Expression<Func<TModel, TProperty>>;

Is it possible to create Expression<Func<TModel, bool>>() which can be used in different htmlHelpers (for instance in CheckBoxFor()), if I have a model object

this HtmlHelper<TModel> htmlHelper

and name of the property (through reflection).

Upvotes: 5

Views: 4035

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063328

Sure:

static Expression<Func<TModel,TProperty>> CreateExpression<TModel,TProperty>(
    string propertyName)
{
    var param = Expression.Parameter(typeof(TModel), "x");
    return Expression.Lambda<Func<TModel, TProperty>>(
        Expression.PropertyOrField(param, propertyName), param);
}

then:

var lambda = CreateExpression<SomeModel, bool>("IsAlive");

Upvotes: 12

Related Questions