简体   繁体   中英

mvc4 System.InvalidOperationException

I am getting this error below.

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

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

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

the exception is triggered below in the SUBSTRING() function

<td class="hidden-desktop">@Html.DisplayFor(modelItem => item.isim.Substring(0,10).ToString());</td>
<td class="hidden-phone hidden-tablet">@Html.DisplayFor(modelItem => item.isim)</td>

I am trying to diisplay the short and long versions of the same text according to the screen size. what am I doing wrong to get the error message? or how should I use the substring() properly?

You don't have to use Html.DisplayFor for a simple string Property. Replace your code with the following:

<td class="hidden-desktop">@item.isim.Substring(0,10)</td>
<td class="hidden-phone hidden-tablet">@item.isim</td>

The other and better option is to define a new isimShort Property in your View Model, and set it to isim.Substring(0,10) in your Controller.

Change it to

<td class="hidden-desktop">@Html.Display("isim", item.isim.Substring(0,10))</td>

DisplayFor expect the argument to be property but Substring() is not a property

Or just

<td class="hidden-desktop">@item.isim.Substring(0,10)</td>

Try changing it to this:

<td class="hidden-desktop">@Html.DisplayFor(modelItem => modelItem.isim.Substring(0,10).ToString());</td>
<td class="hidden-phone hidden-tablet">@Html.DisplayFor(modelItem => modelItem.isim)</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM