Background
The LinkItemCollection class was a truly appreciated addition when EPiServer CMS 5 R2 was released.
Part of the EPiServer.SpecializedProperties namespace the LinkItemCollection class is a property that editors can use to add multiple links to a page.
I've seen numerous variations of implementations aimed at allowing an editor to select an arbitrary number of links and sort them for "Related links" modules and a number of other applications. Remember the MultiPageProperty, anyone? That one's still valid for EPiServer 4, by the way.
However, EPiServer is now shipping a native page property called Link Collection which alleviates the need for such a custom property.
Using the Link Collection property
Add a Link Collection property to your page
First of all, add a new page property of type Link Collection to your page:
Add a couple of links to your page
In the edit interface you can add an arbitrary number of links to other pages, documents, external URLs, etc. You can also easily change the order in which these links appear.
Retrieve your links in code behind
To get the links in a Link Collection is pretty straightforward. Simply cast your Link Collection property into a LinkItemCollection object.
LinkItemCollection links =
((LinkItemCollection)CurrentPage.Property["RelatedLinks"];
Each item in the LinkItemCollection list is a LinkItem object. A LinkItem object resembles the HtmlAnchor control in ASP.NET in terms of properties. For instance, the following code could be used to add an HtmlAnchor control based on a LinkItem object to your page:
foreach (LinkItem link in links)
{
//Create new <a> tag
HtmlAnchor a = new HtmlAnchor()
{
//Set <a> tag properties
HRef = link.Href,
InnerText = link.Text,
Title = link.Title,
Target = link.Target
};
//Add the control to the current page
Page.Controls.Add(a);
}
If you wanted you could instead databind the LinkItemCollection object to a Repeater control, or some other type of templated control.
A word of caution
The original release of EPiServer CMS 5 R2 included a bug which made it impossible to have more than one Link Collection property on a page. If you've tried you will have noticed that having multiple Link Collection properties causes some really weird behavior in edit mode. However, there is a hotfix available from EPiServer Support which resolves this issue.
Update: Here is the hotfix for the LinkItemCollection property