kentico

How do I get a relative URL to a media item from my codebehind?


I have a layout web part which has a "Teaser" field. The "Teaser" field uses a "media selection" form control. In this case the field is set to an image uploaded to one of the sites media libraries.

I want to render that image, so I'm trying to get the relative URL to it in the codebehind:

if (Teaser != Guid.Empty) // Teaser is {8d7fa1ab-b304-474f-9ab9-2e17e8fee84f}
{
    var mediaInfo = MediaFileInfoProvider.GetMediaFileInfo(Teaser, SiteContext.CurrentSiteName);
    // mediaInfo is null so the next line crashes
    var libraryInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(mediaInfo.FileLibraryID);
    string url = MediaFileURLProvider.GetMediaFileUrl(mediaInfo, SiteContext.CurrentSiteName, libraryInfo.LibraryFolder);

The "mediaInfo" variabe is null, so the code crashes.

How can I get a relative URL to my media file?


Solution

  • You cannot add the "Media selection" form control in combination with an field type Guid. Then you need to create an custom form control if you need to have only the Guid.

    But an better solution is add an field with the data type "text" and in combination with the form control "media selection" then adds directly the relative URL inside the field when selecting an image from the media library.

    If you also need the MediaInfo then you can get this object with the parameter "mediaFilePath", like described here : https://devnet.kentico.com/docs/8_2/api/html/M_CMS_MediaLibrary_MediaFileInfoProvider_GetMediaFileInfo_3.htm

    Good luck and if you have more questions you can always ask them here on StackOverflow or on http://devnet.kentico.com/questions-answers.