How can I truncate a string using MVC Html Helpers?
Don't use the html helper. Just do this:
@item.Description.Substring(0, Math.Min(item.Description.Length, 25));
I'm assuming you are in some loop where item
is the current element.
You could do this with an extension method.
public static string Truncate(this string source, int length)
{
if (source.Length > length)
{
source = source.Substring(0, length);
}
return source;
}
Then in your view:
@item.Description.Truncate(25)
you could either truncate the data before it gets to the View, or use this Razor:
@{
var shortDescript = String.Concat(modelItem.Take(25));
}
@Html.DisplayFor(modelItem => shortDescript)