r.r
r.r

Reputation: 7153

ASP.NET MVC string formatting c# - show 20 characters of 100 - trim/cut string

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

Upvotes: 0

Views: 12846

Answers (4)

Geminirand
Geminirand

Reputation: 315

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; }

Upvotes: 1

Trimack
Trimack

Reputation: 4213

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

Upvotes: 2

Ivo
Ivo

Reputation: 3436

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

Upvotes: 2

Simon Steele
Simon Steele

Reputation: 11608

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!

Upvotes: 19

Related Questions