Reputation: 263
I want to limit the number of characters displayed to 25 in this anchor tag :
@Model.Name.Substring(0,25)
But not all the fields have 25 or greater characters, so the Substring() complains when there are fewer. Is there any other way of doing this? Thanks
Upvotes: 0
Views: 1551
Reputation: 11154
Please try with the below code snippet.
@Model.Name.Substring(0,Model.Name.Length > 25 ? 25 : Model.Name.Length)
Upvotes: 1
Reputation: 6079
using System;
public static class StringExtensions
{
public static string SubstringOrFewer(this string str, int n)
{
int max = n > str.Length ? str.Length : n;
return str.Substring(0, max);
}
}
public class Program
{
public void Main()
{
string xx = "0123456789";
Console.WriteLine(xx.SubstringOrFewer(9));
Console.WriteLine(xx.SubstringOrFewer(90));
}
}
Output is:
012345678
0123456789
Upvotes: 1