2013-07-03 31 views
0

我在下面得到這個錯誤。mvc4 System.InvalidOperationException

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. 

異常在SUBSTRING()函數

<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> 

我想根據屏幕尺寸diisplay同一文本的短期和長期的版本低於觸發。我做錯了什麼來獲取錯誤信息?或者我應該如何正確使用substring()?

+0

Html.DisplayFor期望您的模型中有成員(屬性或字段),Substring不是模型的成員。您可能需要添加一個屬性,比如ShortISIM,它返回要輸出的較短版本的字符串。 – emgee

回答

1

將其更改爲

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

DisplayFor期望的說法是財產,但Substring()不是屬性

或者只是

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

「isim」未被識別。它給出了一個錯誤 –

+0

使用你試圖訪問的對象的實例(例如'item')我認爲你是在使用foreach。模型可能會引用您的頁面上的另一個對象 – codingbiz

+0

它的工作原理,我會盡快標記它。 –

1

嘗試將其更改爲這樣:

<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> 
2

您不必爲簡單的字符串Property使用Html.DisplayFor。用以下內容替換代碼:

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

其他更好的選擇是在您的視圖模型在你的控制器來定義一個新isimShort屬性,並將其設置爲isim.Substring(0,10)。

相關問題