0
votes

I have a small trouble. I want to show just a part of a string for example:

Instead: "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua."

Just a: "Lorem ipsum dolor sit amet, consetetur sadipscing..."

Which method can I use to do that?

Thanks for a help and take care, Ragims

4
Do you want it to just truncate the string and add three dots? Or do you want it to break on a word break (i.e. white space?). If so, what rules do you have around determining the closest word break, can it be more than your cut off if that is only 'x' characters away, etc. - Paul Hadfield

4 Answers

2
votes

definitely substring. Trust me, Trim is not enough ;)

19
votes

I use a string extension method to do this. Add a method like this to a static class wherever you keep your helper methods:

    /// <summary>
    /// Trim the front of a string and replace with "..." if it's longer than a certain length.
    /// </summary>
    /// <param name="value">String this extends.</param>
    /// <param name="maxLength">Maximum length.</param>
    /// <returns>Ellipsis shortened string.</returns>
    public static string TrimFrontIfLongerThan(this string value, int maxLength)
    {
        if (value.Length > maxLength)
        {
            return "..." + value.Substring(value.Length - (maxLength - 3));
        }

        return value;
    }

This will trim the front of the string, easy enough to fix if the beginning of your string is more important. Then to use this in your view:

Here is my trimmed string: <%: Model.MyValue.TrimFrontIfLongerThan(20) %>

Hope that helps!

2
votes

What I always do is a "short text" and a long text. To avoid that words get cut off in the middle. I dont know if what your exact requirements are.

If it doesnt matter, use substring

1
votes

When doing this in a grid row, I did this: @item.Body.Remove(300) and add the ellipses after this. Be aware that your starting index must be greater than the value in the field. I'm using this for something where the "Body" field will be between 1000-4000 chars, so I know that 300 will always work. See below:

@foreach (var item in Model) {
    <tr>
        <td>@Html.ActionLink(item.Headline, "Edit", new { id=item.AdvisoryId })</td>
        <td>@Html.Raw(item.Body.Remove(300))...</td>
        <td>@item.AdvisoryStartDate.ToShortDateString()</td>
        <td>@item.AdvisoryType.AdvisoryType</td>
        <td>@item.AdvisoryProvider.AdvisoryProvider</td>
        <td>@item.AdvisoryCategory.AdvisoryCategory</td>
        <td>@Html.ActionLink("View", "Details", new { id=item.AdvisoryId })</td>            
    </tr>
}

MODEL - helps make sure there's no bug

[MinLength(300, ErrorMessage = "Body must be longer than 300 characters.")]
[MaxLength(4000, ErrorMessage = "Body cannot be longer than 4000 characters.")]
public string Body { get; set; }