我正在尝试截断一个长字符串以仅在我的索引页面上显示。显示如下:
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
描述可以有 500 个字符长,但我不能在那个网格布局上显示那么多。我只想显示前 25 个,因为他们可以在“详细信息”页面上看到所有这些,但如果不在模型级别截断它,我似乎无法让它工作。
像这样的东西会很好:
@Html.DisplayFor(modelItem => item.Description.Take(25))
@Html.DisplayFor(modelItem => item.Description.Substring(0,25)
编辑
当我尝试任何一种方法时,我在运行时遇到以下异常。
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
最佳答案
不要使用 html 帮助程序。只需这样做:
@item.Description.Substring(0, Math.Min(item.Description.Length, 25));
我假设您处于某个循环中,其中 item
是当前元素。
关于c# - 如何使用 MVC Html Helpers 截断字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23572631/