Reputation: 11442
How do I provide links in a page to documents within the Sitecore Media Library?
In my template(s) I have a Treelist which allows users to select a number of documents for a given page object. In my sublayout code-behind I iterate over the items in the Treelist field to get their IDs, then use Sitecore.Links.LinkManager.GetItemUrl()
to get the URL to the items. At the moment I simply render the links using a hyperlink, but on clicking the links I get the error saying that no layout was found.
Do I need to create a layout which is an ashx handler to handle downloading the content stream of the media item, or is there something built-in which can do this?
Upvotes: 2
Views: 3767
Reputation: 11
You can have a TreeList of Documents which are of Type "File" and in your code behind you can itterate a loop to fetch the url of that document item (Which has File Type) and than you can get the Media Url of that file item and assign it to the hyperlink .
Here is the code snippet :
List<Item> documentList = your list of selected documents from sitecore
foreach(Item item in documentList)
{
FieldField file = item.Fields["FileField Name"];
if(file != null)
{
if(file.MediaItem != null)
{
hyperlink.NavigateUrl = Sitecore.StringUtil.EnsurePrefix('/',Sitecore.Resources.Media.MediaManager.GetMediaUrl(file.MediaItem));
}
}
}
Upvotes: 0
Reputation: 143
To respond to mdresser and to complete comment of Younes; to ensure the prefix '/' using StringUtil looks like this:
var thumbnailUrl = Sitecore.StringUtil.EnsurePrefix('/',
Sitecore.Resources.Media.MediaManager.GetThumbnailUrl(_thumbnail));
Upvotes: 1
Reputation: 11
Try using Sitecore.Resource.Media.MediaProvider.GetMediaUrl()
.
Or, for each item, cast as MediaItem.
Media folder should be : /~/media/
MediaPath is a property.
Extension is the file extension, etc.
Also take a look at using MediaUrlOptions
.
Upvotes: 1
Reputation: 8560
To generate links to items within the Media Library you should be using MediaManager
. e.g:
string url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(item)
Upvotes: 6