I'm new to Sitecore.. I have created a Page template and add a field for a URL of type General Link. I have created another field for the text for the link (this is standard practice in this project).
I simply want to display the link in my user control but I just cant get it to work. This should be simple but Im going round in circles
Here's an example of the code I've tried ..
ascx :
<asp:HyperLink runat="server" ID="lnkMain"></asp:HyperLink>
ascx.cs:
lnkMain.NavigateUrl = SiteCore.Context.Item.GetGeneralLink("Link1");
lnkMain.Text = item.GetFieldValue("Link1Text");
You should be careful using linkField.Url
since it it will incorrectly render internal links to Sitecore Items and Media. You should instead be using Sitecore.Links.LinkManager.GetItemUrl(item)
and Sitecore.Resources.Media.MediaManager.GetMediaUrl(item)
for those.
It would be better to have a helper (extension) method to return the correct url for you, based on the type of link. Take a look this Sitecore Links with LinkManager and MediaManager blog post which has the correct code you need for this.
For reference:
public static String LinkUrl(this Sitecore.Data.Fields.LinkField lf)
{
switch (lf.LinkType.ToLower())
{
case "internal":
// Use LinkMananger for internal links, if link is not empty
return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty;
case "media":
// Use MediaManager for media links, if link is not empty
return lf.TargetItem != null ? Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem) : string.Empty;
case "external":
// Just return external links
return lf.Url;
case "anchor":
// Prefix anchor link with # if link if not empty
return !string.IsNullOrEmpty(lf.Anchor) ? "#" + lf.Anchor : string.Empty;
case "mailto":
// Just return mailto link
return lf.Url;
case "javascript":
// Just return javascript
return lf.Url;
default:
// Just please the compiler, this
// condition will never be met
return lf.Url;
}
}
Usage:
Sitecore.Data.Fields.LinkField linkField = item.Fields["Link1"];
lnkMain.NavigateUrl = linkField.LinkUrl();
It would be best of course to use <sc:FieldRender>
control and let Sitecore handle it for you, but it looks like you do not have that option.