C# Functions

XHTML and C# Functions

You may use a C# function to create some markup that will be further used in some other functions, page templates or on pages.

Also, in general for CMS functions to be available in Visual Editor for insertion on pages, they must return XHTML. Otherwise they will be only visible in Source Editor.

For these purposes, you may want to consider having your C# function to return XHTML.

As many CMS functions return XHTML, in some cases you may need to use the XHTML parsed rather than raw.

Let’s have a quick look at how you can:

Returning XHTML from C# Functions

If you want to return XHTML from a C# function, you should use XhtmlDocument (Composite.Core.Xml.XhtmlDocument) to create required markup and return it as an XhtmlDocument object.

The XhtmlDocument class is part of C1 CMS API and is inherited from .NET Framework class System.Xml.Linq.XDocument.

You can add XHTML content to XhtmlDocument.Head (<head/> section of the document) and XhtmlDocument.Body (<body/> section of the document) by using the Add method.

public static XhtmlDocument WelcomeUser(string userName)
{
  string welcomeMessage = String.Format("Hi {0}, welcome to my website!", userName);
  XhtmlDocument document = new XhtmlDocument();
  document.Body.Add(
    new XElement(Namespaces.Xhtml + "p", welcomeMessage));
  return document;
}

Listing 13: A sample C# function returning XHTML

Please note XML namespaces are important here. In the above sample an HTML <p /> element is created as Namespaces.Xhtml+"p". Namespaces.Xhtml ensures that the <p/> element is in the XHTML namespace.

When you use XhtmlDocument as the C# function’s return value, it will also be available in Visual Editor so you will not need to switch to the Source mode.

As the function on a page or in a page template is nothing but markup (<f:function />), you can also use XhtmlDocument to build the markup of a certain CMS function and return it as a value of your C# function.

Parsing XHTML in C# Functions

If you use a value, for example, from a data field, that contains markup (XhtmlDocument, XElement etc), you should consider using XElement.Parse method to parse it first.

So rather than using raw markup:

myXelement.Add(teamMember.HtmlDescriptionField);

use it parsed:

myXelement.Add(XElement.Parse(teamMember.HtmlDescriptionField);

As to ASP.NET Web Forms and MVC scenarios, you should print the value raw as you normally would.