问题描述:

I am on Sitecore 7.2

I am experiencing issues trying to retrieve media URL.

I have a template (PageBanner) with just one field called BannerImage. Field type is Image.

Another template named Homepage inherits this template PageBanner.

A content item Home uses template Homepage. I can see the BannerImage field as a part of the Home content item. An image has been assigned to this field as well.

Now, the back-end bit where the issue is encountered.

homeItem.Field["BannerImage"] returns image item.

homeItem["BannerImage"] returns empty string.

If I try to cast it to ImageField -(ImageField)homeItem.Field["BannerImage"], the resultant ImageField item doesn't have MediaItem or any other field set.

I can do :

var imageFieldItem = Sitecore.Context.Database.GetItem(homeItem.Fields["BannerImage"].ID);

var mediaUrl = MediaManager.GetMediaUrl(imageFieldItem);

But that gives me a dynamic media url in the form of -~/media/a2c15f35836746f398e772c81d040607.ashx

I am looking to get the media URL by path.

Any idea what am I missing here?

网友答案:

You are making the correct call to get the URL using the MediaManager but you need to pass the inner MediaItem to the GetMediaUrl() method:

string imageURL = string.Empty;
Sitecore.Data.Fields.ImageField imageField = homeItem.Field["BannerImage"];
if (imageField != null && imageField.MediaItem != null)
{
    Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);
    imageURL = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));
}

As for the dynamic URL being generated, if it is in Edit mode then this is normal, Check in Normal mode that the media URL is fully rendered.

网友答案:

Try this code out in some utility class.

var imageUrl = GetImageUrl(homeItem, "BannerImage" false);

    public static string GetImageUrl(Item item, string fieldname, bool includeServerUrl)
    {
        // do the checks
        if (item == null) { return ""; }
        if (fieldname.Length == 0) { return ""; }

        // create media options
        Sitecore.Resources.Media.MediaUrlOptions mediaUrlOptions = new Sitecore.Resources.Media.MediaUrlOptions { AlwaysIncludeServerUrl = true };
        mediaUrlOptions.AbsolutePath = true;

        // do we want to include the FQDN?
        if (includeServerUrl)
            mediaUrlOptions.AlwaysIncludeServerUrl = true;

        // convert to image field
        Sitecore.Data.Fields.ImageField imagefield = item.Fields[fieldname];

        if (imagefield == null) { return ""; }

        // get the item so we can process it
        Item mediaitem = Sitecore.Context.Database.GetItem(imagefield.MediaID);
        if (mediaitem == null) { return ""; }

        // pass in the item with the options to get the URL
        string mediaurl = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaitem, mediaUrlOptions);
        if (mediaurl == null) { return ""; }

        return mediaurl;
    }
相关阅读:
Top