How to create an expression <Func <TModel, TProperty >>;

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

 this HtmlHelper<TModel> htmlHelper 

and the name of the property (via reflection).

+4
source share
1 answer

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"); 
+11
source

All Articles