Razor’s @helper syntax has made it pretty easy to create your own helper functions for use in your views. For example open your ".cshtml" file and add the following code directly after the @model line.
@helper Truncate(string input, int length) { if (input.Length <= length) { @input } else { @input.Substring(0, length)... } }
This helper method takes a string and a maximum length to allow. If the text supplied is shorter than the length specified, the helper outputs it as-is. If it is longer, then it truncates the text and renders “…” for the remainder.
Now you can refer the Truncate method in your view. So if your Model has a Title property
@Truncate(Model.Title, 25)
Read more>>
Make the helper method accessible to all views by defining it in a CSHTML file under App_Code folder. Click here to read more >>
No comments:
Post a Comment