Pat*_*ick 3 c# asp.net-mvc razor
如果它比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
Run Code Online (Sandbox Code Playgroud)
谢谢.
任何字符串.看到这里.
而对于你的代码......
@(Model.Council.Length>10 ? Model.Council.Substring(0, 10)+"..." : Model.Council)
Run Code Online (Sandbox Code Playgroud)
这是您可以使用的辅助方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
只需从CSHTML中调用它:
<p>@StringHelper.TruncateWithEllipsis(Model.Council, 10)</p>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5798 次 |
| 最近记录: |