Setting Sitecore ImageField

Update: this post uses an older version of the Sitecore API. For an up-to-date solution, please see this updated article.

Recently I had to write something to allow users to upload their own content on a Sitecore site. Not an unusual, or especially difficult, piece of functionality but one thing that did give me a bit of trouble was associating uploaded images (in the media library) with the Sitecore item’s image field.

Originally I tried setting the media ID and the media path properties, but that didn’t quite work.  Eventually I found that you have to set the media ID, media path, source, and a custom attribute (“showineditor“).  I was surprised that it wasn’t easier to assign a media file to an ImageField object, but that’s easily resolved using extension methods introduced in .Net 3.5.  For the lazier among us, I’ve included a small snippet of code that does the important stuff.  This code is written for Sitecore 5.3, but should work on Sitecore 6.x with minor tweaking if some nicer methods haven’t already been put in place.  Obviously, production code should be made a bit robust than what’s below, which has no exception handling and assumes the item is already in editing mode.

public void AssignMediaItem(ImageField field, Item mediaItem)
{
    field.MediaID = mediaItem.ID;
    MediaUrlOptions options = new MediaUrlOptions();
    field.Src = MediaManager.GetMediaUrl(mediaItem, options);
    field.MediaPath = mediaItem.Paths.MediaPath;
    field.SetAttribute("showineditor", "1");
}

2 thoughts on “Setting Sitecore ImageField”

  1. Thank you sir. I was having the same issue for a client using Foundry. Spent a few hours trying to track down the reason, as the documentation was lacking in this area.

  2. For Sitecore 6.5 Src and MediaPath are depricated. From what you provided here, I created the following extension method:
    public static class SitecoreFieldExtentions
    {
    public static void AssignMediaItem(this ImageField field, Item mediaItem)
    {
    field.MediaID = mediaItem.ID;
    field.SetAttribute(“showineditor”, “1”);
    }
    }

Comments are closed.