I am trying to truncate a text field that is sometimes extremely large or at other times it is null from the database i.e
@Html.DisplayFor(modelItem => item.MainBiography)
and replace with three dots at the end.
I have tried the substring function but keep getting errors.
Any pointers, thanks!
Update:
The ... is not hugely important so I tried using
@Html.DisplayFor(modelItem => item.MainBiography.Substring(0,10))
and get the following error codes:
System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions. Source=System.Web.Mvc –
Try using
Html.Display
instead ofDisplayFor
like this:By the way your both lambda statements are invalid.Parameter names should be the same.
Not like this:
It should be:
Or:
You may write a string extension method and call that on your model property (of string type). You can pass the limit for your substring operation.
and in your view, import the namespace where you have your extension method and call the method on your string property.
DisplayFor
requires an expression that represents a property.You can add a property to the model:
Then in your view just do:
You're better off creating a different property in the model, to pick up the
MainBiography
and eventually cut it short.Like this:
Usage would be
Another approach would be to build a full-fledged view model, but I find it overkill more often than not.