MVC4 templates can only be used with field access.

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!

+6
source share
1 answer

A model.Number used to convert model.Number from int to object . You can verify this by looking at the expression with the debugger

 .Lambda #Lambda1<System.Func`2[Model,System.Object]>(Model $model) { (System.Object)$model.Number } 

If you want to get the correct expression, you should use Expression<Func<Model, int>>

 Expression<Func<Model, int>> numberExpression = model => model.Number; 

This expression has been translated to

 .Lambda #Lambda1<System.Func`2[Model,System.Int32]>(Model $model) { $model.Number } 
+3
source

All Articles