2

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?

4 Answers 4

6

To generate links to items within the Media Library you should be using MediaManager. e.g:

string url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(item)
2
  • 1
    Don't forget to use the Sitecore StringUtil to ensure the prefix!
    – Younes
    Apr 19, 2011 at 6:34
  • @Younes thanks for that tip, what methods in particular should I be looking at in StringUtil ? On a related note, I've just started using this method in a bilingual website and am getting more problems. Apr 19, 2011 at 14:58
1

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.

1
  • Are there any properties in particular I should be looking at in the MediaUrlOptions class? Apr 20, 2011 at 9:05
1

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));
0

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));
         }
     }
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.