I want to display some text in my view, but if the text is more than 600 characters long, I want to truncate and add an ellipsis at the end. If the text is less than 600 characters, I will display the whole string unmodified.
I was thinking something along the lines of this:
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;
}
}
The above code compiles, but when I try to run it my app times out with a "connection refused" error message. If I change the property to just public string Description { get; set; }
, my app runs.
I need the setter, because elsewhere in my app, I modify the Description
property in the controller.
UPDATE
Thanks to Steve for the solution. However, when the truncation did work, I realised that sometimes I actually want to have the entire text in the view. So I made an additional method which use the original Description
instead of 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 "";
}
}
Your code in the get accessor will raise a Stack Overflow exception because to measure the length of the Description you call the get accessor and this will never end until the stack overflow stops your code.
To solve your problem use a backend variable and work with it
private string _dsc = "";
public string Description
{
get
{
int txtLen = _dsc.Length;
int maxLen = 600;
if (txtLen > 0)
{
string ellipsis = txtLen > maxLen ? "..." : "";
return _dsc.Substring(0, txtLen > maxLen ? maxLen : txtLen) + ellipsis;
}
else
{
return "";
}
}
set
{
_dsc = value;
}
}