Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions

大憨熊 提交于 2019-12-22 01:40:53

问题


This part of code is not working

@foreach (var item in Model) {
        <tr>
            <td>
            @Html.DisplayFor(modelItem=>item.Registrations.Count())
         </td>

and throws an error

[InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.]

But this part of code below is working as a charm.

@foreach (var item in Model) {
    <tr>
        <td>
           @item.Registrations.Count()
        </td>

Is there anybody who can explain why is so?


回答1:


I'd think it's because you're using modelItem => item.Registrations.Count(). DisplayFor wants an expression that refers to a member of your model, not a function on a member's method as the model binder wouldn't know how to serialize the data on the way back (i.e. after a form post).

EDIT: I'd weirdly had the same error but for a completely different reason which turned out to be that the DateTime needed to be nullable




回答2:


I just saw this error message occur when attempting to generate a control for an inappropriate data type, for example, when trying to use (in VB.NET syntax):

@Html.CheckBoxFor(Function(model) model.IsLotTraced)

Where IsLotTraced is declared as

Public Property IsLotTraced As String

The error goes away when it's changed to

Public Property IsLotTraced As Boolean



回答3:


Yeah, After a form post think it's because you're using modelItem=>item.Registrations.Count(). DisplayFor is an expression that refers to a member of your model, not a function on a member's method as the model binder wouldn't know how to serialise the data on the way back.



来源:https://stackoverflow.com/questions/9925728/templates-can-be-used-only-with-field-access-property-access-single-dimension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!