4

X文字より長い場合、Razor CSHTMLページで文字列をフォーマットするにはどうすればよいですか:

<p>@Model.Council</p> 

Example for an X = 9

-> if Council is "Lisbon", then the result is "<p>Lisbon</p>"
-> if Council is "Vila Real de Santo António", then the result is "<p>Vila Real...</p>" with the title over the <p> "Vila Real de Santo António" showing the complete information

ありがとう。

4

4 に答える 4

5

使用できるヘルパー メソッドを次に示します。

public static class StringHelper
{
    //Truncates a string to be no longer than a certain length
    public static string TruncateWithEllipsis(string s, int length)
    {
        //there may be a more appropiate unicode character for this
        const string Ellipsis = "...";

        if (Ellipsis.Length > length)
            throw new ArgumentOutOfRangeException("length", length, "length must be at least as long as ellipsis.");

        if (s.Length > length)
            return s.Substring(0, length - Ellipsis.Length) + Ellipsis;
        else
            return s;
    }
}

CSHTML 内から呼び出すだけです。

<p>@StringHelper.TruncateWithEllipsis(Model.Council, 10)</p>
于 2013-05-27T01:43:13.687 に答える