I have an MVC model like this
public class Model { public string Name {get;set;} public int Number {get;set;} }
I get an error
Templates can only be used with access to a field, access to properties, an index of a one-dimensional array, or one-parameter expressions of a custom indexer.
when trying to create a label for a numeric field with a model lambda expression stored in a variable.
For example, in my opinion, I:
@Html.LabelFor(model => model.Name) // Works fine @Html.LabelFor(model => model.Number) // Works fine @{ Expression<Func<Offer, object>> nameExpression = model => model.Name; Expression<Func<Offer, object>> numberExpression = model => model.Number; } @Html.LabelFor(nameExpression) // Works fine @Html.LabelFor(numberExpression) // Error!
I noticed that with a debugger, I noticed that the lambda expression is model => Convert(model.Number) instead of model => model.Number , but this only happens to determine the types from what I can say since I tested with integers (with null and non-null) and DateTime objects. NodeType seems to be for Convert lambda expression, for Member access strings.
I know the cause of the error itself, but I do not know what causes the compiler to evaluate model=>model.Number to model => Convert(model.Number) .
Thanks!
source share