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");
It'd be easier if you use the Link control:
That way, you don't have to do any code-behind stuff and you'll be able to use the Page Editor as well.
As of Sitecore 7.2 there is an alternative to linkField.Url:
http://techitpro.com/uncategorized/sitecore-7-2-changes/
You need to get the
Linkfield
value of the item and than get theLinkField
type of that item. This will give you the type of link either an "Internal", "external", "mailto" and based on that can get the url of the link field as this is mentioned by @jammykam.Same thing you can do to retrieve the
LinkText
as well.For Reference :
You can use below
It will work for you.
When you assign a value to a GeneralLink field of an item there is a field labeled "Link Description" in the Internal Link dialog that pops up. Fill in that value then use:
That's it. Everything is "wired-up" for you, auto-magically.
You should be careful using
linkField.Url
since it it will incorrectly render internal links to Sitecore Items and Media. You should instead be usingSitecore.Links.LinkManager.GetItemUrl(item)
andSitecore.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:
Usage:
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.