In many cases, you may need to process values and display them in a different format or add custom conditions. The following example shows you how to create a custom function that will return the first N characters of a text and how to use it in a transformation.
Open the web project in Visual Studio. Create a new folder under the App_Code folder and call it as your site code name. Right-click the folder and choose Add New Item. Choose to add a new Class and call it MyFunctions.cs (custom transformation functions can be developed only in C# at this moment).
Paste the following code to the MyFunctions.cs file:
[C#]
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
/// <summary> /// Summary description for MyFunctions /// </summary> public static class MyFunctions { public static string TrimText(object txtValue, int leftChars) { if (txtValue == null | txtValue == DBNull.Value) { return ""; } else { string txt = (string) txtValue; if (txt.Length <= leftChars) { return txt; } else { return txt.Substring(0, leftChars) + "..."; } } } } |
Please note: The function must be defined as static so that you can easily call it from the transformation.
Then, go to Site Manager -> Development -> Document types -> News -> Transformations. Edit the preview transformation and change its code like this:
[C#]
<b><a href="<%# GetDocumentUrl() %>"> <%# Eval("NewsTitle") %></a></b> (<%# GetDate("NewsReleaseDate") %>)<br/> <i> <%# MyFunctions.TrimText(Eval("NewsSummary"), 10) %> </i> <br/> |
Click OK to save. Go to the live site and see the page with news listing. As you can see, the news summary text is truncated to the first 10 characters.
In this topic, you have learned how to write your own transformation methods.