如何限制 html.encode 显示的字符数?
<%= Html.Encode(item.LastName.Substring(1,30))%>
错误:索引和长度必须引用字符串中的位置。
您需要检查字符串长度是否大于 30,否则您指定的长度将超出字符串末尾...(假设您不想省略,我还将您的起始索引更改为 0第一个字符)
<%= Html.Encode(item.LastName.Substring(0,
item.LastName.Length > 30 ? 30 : item.LastName.Length))%>
你也可以做类似的事情
<%= Html.Encode(item.LastName.Substring(0, Math.Min(item.LastName.Length, 30)) %>
节省一些字节
<%= Html.Encode(item.LastName.Substring(0, item.LastName.Length > 30 ? 30 : item.LastName.Length))%>
如果要检查 null,请改为执行以下操作:
<%= Html.Encode(
item.LastName == null ? string.Empty :
item.LastName.Substring(0, item.LastName.Length > 30 ? 30 : item.LastName.Length))%>