Search code examples
imagesitecoreglass-mappersitecore-mvc

How to programmatically create an instance of the Glass.Mapper.Sc.Fields.Image class?


I'm working with a Sitecore MVC website and in a controller, I'm trying to programmatically populate the Src property of the Glass.Mapper.Sc.Fields.Image class. However, it was annoyingly declared with only a public getter and an internal setter:

public string Src { get; internal set; }

Note also that there is only a parameterless constructor in this class. There must therefore be another way to set this value internally, but after an exhaustive search online, I couldn't find anything that worked.

Note that in the controller, I have all of the values that are required to fully populate the Image object, including the Sitecore item ID. I also have access to the parent Sitecore item of type Sitecore.Data.Fields.ImageField that contains the data for the Image object.

I've tried the following, but it returns an empty Image instance.

SitecoreService sitecoreService = new SitecoreService(database);
Image image = sitecoreService.GetItem<Image>(imageField.InnerField.ID.Guid);

And when I tried this, it creates a new Image object with its dimension and Alt fields correctly set, but not the Src property, for some reason.

Image img = sitecoreService.GetItem<Image>(imageField.MediaItem.ID.Guid);
var parent = imageField.MediaItem.Parent;

Please let me know how I can programmatically set the Src property of this Image class, or convert the Sitecore field into an Image instance.


UPDATE >>>

I followed @DrazenJanjicek's advice and managed to map the parent item using the sitecoreService.GetItem method, which successfully populated all of the Image properties for me.


Solution

  • I think creating the proper Glass type from your Sitecore item makes more sense and simply use the Image property. There is no simple API for creating only the Image type. You can do that but in the end Glass will create the outer type first.