如何限制Eval中的文本字符串
我有一个带有如下设置的导航属性的超链接:
NavigateUrl=''
如何将字符串限制为140个字符? 我试过这个Eval(“My Text”)。ToString()。Substring(0,140)但是如果字符串长度小于140个字符,它会抛出exception。
还有另一种可能性:
Eval("My Text").ToString().PadRight(140).Substring(0,140).TrimEnd()
编辑:
我也喜欢LINQ:
Eval("My Text").ToString().Take(140).Aggregate("", (x,y) => x + y)
用它 (:
< % # Eval("MyText").ToString().Length <= 30 ? Eval("MyText") : Eval("MyText").ToString().Substring(0, 30)+"..." % >
该死的我喜欢LINQ:
string.Concat('<%# Eval("My Text") %>'.ToString().Where((char, index) => index < 140))
您可以尝试Truncate方法,如下所示:
C#截断字符串
只需在source参数之前添加this
关键字,即可将其转换为扩展方法。 这是一种更复杂的方法,但在需要在其他地方重复使用的情况下可能很有价值……
在你的情况下,你有:
NavigateUrl='<%# Eval("My Text").ToString().Truncate(140) %>'
完整的控制台测试应用
using System; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string test1 = "A really big string that has more than 140 chars. This string is supposed to be trunctaded by the Truncate extension method defined in class StringTool."; Console.WriteLine(test1.Truncate(140)); Console.ReadLine(); } } /// /// Custom string utility methods. /// public static class StringTool { /// /// Get a substring of the first N characters. /// public static string Truncate(this string source, int length) { if (source.Length > length) { source = source.Substring(0, length); } return source; } /// /// Get a substring of the first N characters. [Slow] /// public static string Truncate2(this string source, int length) { return source.Substring(0, Math.Min(length, source.Length)); } } }
输出:
A really big string that has more than 140 chars. This string is supposed to be trunctaded by the Truncate extension method defined in class
类似于Leniel的答案,但有点扭曲….有时我想附加一个省略号来certificate显示的字符串已被截断。
/// /// Converts the value of the specified string to a truncated string representation /// /// The specified string /// Integer specifying the maximum number of characters to retain from the specified string. /// Determines whether or not to append an ellipsis to the truncated result. If the specified string is shorter than the length parameter the ellipsis will not be appended in any event. /// A truncated string representation of the specified string. public static String Truncate(this String source, int length, bool appendEllipsis = false) { if (source.Length <= length) return source; return (appendEllipsis) ? String.Concat(source.Substring(0, length), "...") : source.Substring(0, length); }
- Uploadify ashx文件Context.Session获取null
- 为什么我在这里“无法访问封闭的流”?
- 在MVC4路由中使用点“。”字符
- 关闭Word文档时出错:“消息filter指示应用程序正忙。”
- asp.net c#生成用户控制参数
- 使用C#/ ASP.NET创建Scaffold代码的最快方法
- 从模型validation中排除类型(示例DbGeography)以避免InsufficientExecutionStackException
- System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)拒绝访问
- Response.WriteFile – 写出一个字节流