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 –
You're better off creating a different property in the model, to pick up the MainBiography
and eventually cut it short.
Like this:
// This is your property (sampled)
public string MainBiography { get; set; }
//How long do you want your property to be at most ?
//(Best practice advices against magic numbers)
private int MainBiographyLimit = 100;
//You probably need this if you want to use .LabelFor()
//and let this property mimic the "full" one
[Display(Name="Main Biography")]
public string MainBiographyTrimmed
{
get
{
if (this.MainBiography.Length > this.MainBiographyLimit)
return this.MainBiography.Substring(0, this.MainBiographyLimit) + "...";
else
return this.MainBiography;
}
}
Usage would be
@Html.DisplayFor(item => item.MainBiographyTrimmed)
Another approach would be to build a full-fledged view model, but I find it overkill more often than not.
DisplayFor
requires an expression that represents a property.
You can add a property to the model:
public string MainBiographyTrimmed
{
get
{
if (MainBiography.Length) > 10
return MainBiography.Substring(0, 10) + "...";
}
}
Then in your view just do:
@Html.DisplayFor(item => item.MainBiographyTrimmed)
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.
public static class StringExtensions
{
public static string SubStringTo(this string thatString, int limit)
{
if (!String.IsNullOrEmpty(thatString))
{
if (thatString.Length > limit)
{
return thatString.Substring(0, limit);
}
return thatString;
}
return string.empty;
}
}
and in your view, import the namespace where you have your extension method and call the method on your string property.
@Html.DisplayFor(modelItem => item.MainBiography.SubStringTo(10))
Try using Html.Display
instead of DisplayFor
like this:
@Html.Display(item.MainBiography.Substring(0, 10), null, "MainBiography")
By the way your both lambda statements are invalid.Parameter names should be the same.
Not like this:
@Html.DisplayFor(modelItem => item.MainBiography)
It should be:
@Html.DisplayFor(modelItem => modelItem.MainBiography)
Or:
@Html.DisplayFor(item => item.MainBiography)