Patrick Patrick - 21 days ago 8
C# Question

Replace end of string with dots if word is longer then X

How can I format a string in a Razor CSHTML page if it's longer then X caracters:

<p>@Model.Council</p>

Example for an X = 9

-> if Council is "Lisbon", then the result is "<p>Lisbon</p>"
-> if Council is "Vila Real de Santo António", then the result is "<p>Vila Real...</p>" with the title over the <p> "Vila Real de Santo António" showing the complete information


Thanks.

Answer

for any string. See here.

And for your code...

@(Model.Council.Length>10 ? Model.Council.Substring(0, 10)+"..." : Model.Council)