当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Display x words from html encoded text

问题描述:

I am using the following code to display my html encoded text from a database:

@Html.Raw(HttpUtility.HtmlDecode(@item.Content))

What I want to do now is to display for instance only 20 words of the content and and "..." at the end. How should I do this? I was thinking about adding a helper for IHtmlString but I don't know how to return the x words for IHtmlString

网友答案:

How should I do this?

You could write a custom HTML helper that will have the responsibility to parse the input string into constituent words and take the first x of them:

public static class HtmlExtensions
{
    private readonly static Regex _wordsRegex = new Regex(
        @"\s", RegexOptions.Compiled
    );

    public static IHtmlString FormatMessage(
        this HtmlHelper htmlHelper, 
        string message, 
        int count = 20
    )
    {
        if (string.IsNullOrEmpty(message))
        {
            return new HtmlString(string.Empty);
        }

        var words = _wordsRegex.Split(message);
        if (words.Length < count)
        {
            return new HtmlString(htmlHelper.Encode(message));
        }

        var result = string.Join(
            " ", 
            words.Select(w => htmlHelper.Encode(w)).Take(count)
        );
        return new HtmlString(result + " ...");
    }
}

which could be used in your view:

@Html.FormatMessage(item.Content)

or if you wanted to specify a different number of words to take:

@Html.FormatMessage(item.Content, 5)
分享给朋友:
您可能感兴趣的文章:
随机阅读: