我想在视图中显示一些文本,但是如果文本长度超过600个字符,我希望截断并在末尾添加省略号。如果文字少于600个字符,我将显示未修改的整个字符串。
我在想一些类似的事情:
public string Description
{
get
{
int txtLen = Description?.Length ?? 0;
int maxLen = 600;
if (txtLen > 0)
{
string ellipsis = txtLen > maxLen ? "…" : "";
return Description.Substring(0,txtLen > maxLen ? maxLen : txtLen) + ellipsis;
}
else
{
return "";
}
}
set
{
Description = value;
}
}
上面的代码可以编译,但是当我尝试运行它时,我的应用程序超时并显示“拒绝连接”错误消息。如果将属性更改为public string Description { get; set; }
,则我的应用程序将运行。
我需要设置器,因为我在应用程序的其他地方,都修改了控制器中的Description
属性。
更新
感谢史蒂夫的解决方案。但是,当截断起作用时,我意识到有时我实际上希望在视图中显示整个文本。因此,我提出了另一种方法,该方法使用原始的Description
而不是private string _dsc
:
public string Description { get; set; }
public string DescriptionTruncate(int maxLen)
{
int txtLen = Description?.Length ?? 0;
if (txtLen > 0)
{
string ellipsis = txtLen > maxLen ? "…" : "";
return Description.Substring(0,txtLen > maxLen ? maxLen : txtLen) + ellipsis;
}
else
{
return "";
}
}