I am trying to truncate a long string for display only on my index page. It is shown like so:
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
The Description can be 500 characters long but I can't show that much on that grid layout. I'd like to show just the first 25 as they can see all of it on the Details page but I cannot seem to get it to work with out truncating it at the model level.
Something like this would be nice:
@Html.DisplayFor(modelItem => item.Description.Take(25))
@Html.DisplayFor(modelItem => item.Description.Substring(0,25)
EDIT
I'm getting the following exception at Runtime when I try either method.
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.
Html.DisplayFormust reference an actual property, not a specific value. In other words, you can only do@Html.DisplayFor(m => item.Description), not@Html.DisplayFor(m => item.Description.Substring(0, 25)). You don't need to useHtml.DisplayForfor this, though, so you can just write@item.Description.Substring(0, 25). However, bear in mind @48klocs's comment to Nathan A's answer.Take()returns aIEnumerable<char>, not a string.Substring()is more suited for this.