I am trying to make a label for a dynamic property using an html helper from the razor engine. The view model is not strongly typed. My knowledge of lambda expressions is not very strong and I am unsure how to produce a dynamic expression that will fit this situation.
public class someModel<TEntity> where TEntity : class
{
public TEntity Entity { get; set; }
}
—-
@model dynamic
@{
string property = "FirstName";
}
@Html.LabelFor( m => m.Entity.property )
Which throws the error An expression tree may not contain a dynamic operation.
I looked into making dynamic expression trees but was unsure if that was overkill or necessary. How can I access properties of the Entity by using strings?
Entity could be a number of different types of classes. Those classes have fully defined data annotations such as [Display(Name = "Some Name")] and the reason I am trying to use LabelFor is to have access to those data annotations.
This is impossible. You cannot use lambda expressions nor strongly typed helpers with dynamic values. You will have to use the weakly typed versions of those helpers:
Yes, once you stop using strongly typed view models, lots of things and habits will have to change.