Getting Images

Getting Images

Getting Images

This snippet uses the context database instead of specifying the database to use - presentation components that retrieve content for display almost always access the context database rather than referencing a database by name.

This snippet uses a fields collection to reference the field:

  • Returns null if the field does not exist or the field value is null
  • Does not generate inline editing controls for the Page Editor
  • Useful for field types other than simple field types

  1. Create an object for the database using the context database
  2. Create an object for the target item in the database- replace itempath with the relative path to the item in the Content Tree, such as “home/about/item1” or start the path with a backslash (/) to indicate an absolute path, such as “/sitecore/content/home/about/item1”– a null value will be set in either case if the item does not exist - Sitecore does compare case when evaluating item paths


C# Web Control Code

Sitecore.Data.Database db = Sitecore.Context.Database;

Sitecore.Data.Items.Item item = db.GetItem("itempath");

 Sitecore.Data.Fields.ImageField image = item.Fields["imagefield"];

if (image!=null && image.MediaItem!=null)

{

      Sitecore.Data.Items.MediaItem image = new              Sitecore.Data.Items.MediaItem(imageField.MediaItem);

      string src = Sitecore.StringUtil.EnsurePrefix('/',            Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));

      if (!string.IsNullOrEmpty(src))

      {

             string imgTag = String.Format(@"<img src=""{0}"" alt=""{1}"" />", src, image.Alt);

      }

}