简体   繁体   中英

How to truncate text in asp.net label inside DataList using jQuery and/or C#

I am looking to crop some text in a label inside a DataList.

<asp:Label runat="server" Text='<%# Eval("Description") %>'></asp:Label>

I would love for my description to be cropped if length of description exceeds 100 characters and a "show more" link to appear ("show less" is not necessary). Once "Show more" is clicked the full description should appear on the same page (this is where I would love for some jQuery to be used)

Can anyone help me get started on a solution for this problem?

I know this is an old question, but for answers sake:

public static class Extensions
{
    /// <summary>
    /// Truncate a value if it is a string.
    /// </summary>
    /// <param name="value">The value to check and truncate.</param>
    /// <param name="length">The length to truncate to.</param>
    /// <param name="appendEllipses">Append ellipses to the end of the value?</param>
    /// <returns>A truncated string, if not a string the object value.</returns>
    public static object Truncate(this object value, int length, bool appendEllipses = true)
    {
        // Are we dealing with a string value?
        var result = value as string;

        // Yes? truncate, otherwise pass through.
        return result != null ? Truncate(result, length, appendEllipses) : value;
    }

    /// <summary>
    /// Truncate a value if it is a string.
    /// </summary>
    /// <param name="value">The value to check and truncate.</param>
    /// <param name="length">The length to truncate to.</param>
    /// <param name="appendEllipses">Append elipses to the end of the value?</param>
    /// <returns></returns>
    public static string Truncate(this string value, int length, bool appendEllipses = true)
    {
        var result = value;

        // Too Long?
        if (value.Length > length)
        {
            // Truncate.
            result = value.Substring(0, length);

            // Add Ellipses, if needed.
            if (appendEllipses) { result = result + " ..."; }
        }

        return result;
    }
}

You can you the second method like so:

<%# Eval("Description").ToString().Truncate(10) %>

Or to avoid clutter you can use the first method like so:

<%# Eval("Description").Truncate(10) %>

I'm not 100% about adding extension methods to the object class, tends to be a pain by popping up everywhere, hence why I gave it as an option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM