I have a field which can contain internal link, media link, external links etc and normally we sort it out by providing sc:Link the item and the respective field and it resolves the url accordingly.
If I wana resolve the url programmatically (to serialize and send over using web service) what do I need to do?
I would really appreciate tips or pointers towards the right direction.
There is nothing in the Sitecore API directly that will achieve what you need but you can create a helper method to achieve what you require. I'm assuming you are using a LinkField
.
There is a great article on Brian Pedersen's blog about Sitecore Links with LinkManager and MediaManager. Code snippet below taken from his article:
Sitecore.Data.Fields.LinkField lf = Sitecore.Context.Item.Fields["Link"];
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;
}
If you need to resolve the internal URL to be fully qualified with the domain name then pass in UrlOptions.SiteResolving=True
to the LinkManager
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With