1

I have an image field associated to my custom user profile template, but I am having trouble accessing the value of it programmatically.

I have tried the following...

Context.User.Profile.GetCustomProperty("Profile Image");

However, it only returns the raw value: <image mediaid=\"{CCDD1D99-5649-41A1-A177-B3902C1830B2}\" /> of the Media item in the Media Library and I am having trouble accessing it to retrieve the image src to render the image on my profile page.

I have tried looking around to see what is acceptable as next steps but have come up empty handed. Would anyone have any ideas how to retrieve the profile image src to render to my view?

2 Answers 2

4
  • On backend you can do:
var rawValue = Context.User.Profile.GetCustomProperty("Profile Image");
var itemId = Sitecore.Xml.XmlUtil.GetAttribute("mediaid", XmlUtil.LoadXml(rawValue));
var item = Context.Database.GetItem(itemId);

var imageUrl = MediaManager.GetMediaUrl(new MediaItem(item));
  • On frontend (if you are working in JSS or don`t have access to backend) you can parse mediaId from string and build image ulr in format "/-/media/CCDD1D99564941A1A177B3902C1830B2.ashx"
0

Unfortunately if you store the image on profile, you don't have an item instance or the image field. I'm afraid you will have to use some kind of parser for the xml. You can try to use the code like:

public class ImageFieldParser
{
    private XmlDocument _xmlDocument;

    public ImageFieldParser(string imageFieldValue)
    {
        if (!string.IsNullOrEmpty(imageFieldValue))
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(imageFieldValue);
                _xmlDocument = xmlDocument;
            }
            catch (Exception ex)
            {
                Log.Error($"Attempted to load invalid xml: '{imageFieldValue}'", ex, this);
            }
        }
    }

    public string MediaItemUrl
    {
        get
        {
            if (_xmlDocument == null || string.IsNullOrEmpty(GetAttribute("mediaid")))
                return null;

            if (!ID.TryParse(GetAttribute("mediaid"), out ID id))
                return null;

            var item = Database.GetDatabase("web").GetItem(id);

            if (item == null)
                return null;

            return MediaManager.GetMediaUrl(new MediaItem(item));
        }
    }

    public string GetAttribute(string name)
    {
        return _xmlDocument?.DocumentElement?.Attributes[name].Value.ToLower();
    }
}

and then use it with

var imageUrl = new ImageFieldParser(RAW_VALUE).MediaItemUrl;

I haven't tested the code so I cannot guarantee it will work.

Your Answer

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

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