Programatically attaching media to content

I think I’m probably missing something really obvious, but I can’t for the life of me get this working.

I’m creating content programatically, and importing media files to be attached to it through a MediaPicker3 property editor.

The media imports into the media library without issue, and returns me an IMedia object for each one.

All the docs/stack overflow posts etc that I find refer to just doing something like

content.SetValue("propertyAlias", media.GetUdi())

(where content and media are the IContent and IMedia objects, respectivly).

However, the property in question supports multiple media items, so I assumed that passing a IEnumerable would be the way to go - but the property is always empty after the content is created. I’ve tried passing it as an explicit array (GuidUdi[]) and passing the entire IMedia object instead of just the Udi (IEnumerable<IMedia> and IMedia[]).

Anyone know what am I missing?

OK, so after much trial and error I’ve figured it out.
The MediaPicker expects a JSON array of objects with the following structure;

[
  {
    "key" = "00000000-0000-0000-0000-000000000000",
    "mediakey" = "00000000-0000-0000-0000-000000000000",
  },
  {
    "key" = "00000000-0000-0000-0000-000000000000",
    "mediakey" = "00000000-0000-0000-0000-000000000000",
  },
]

So I modified my code as follows;

content.SetValue("propertyAlias", JsonConvert.SerializeObject(listOfMedia.Select(media => new {
  key = Guid.NewGuid(),
  mediaKey = media.key,
})));

And that’s done the trick.

If I may give you a suggestion; if you run into these kind of issues, just check the Umbraco source code. It’s relatively easy to find out what the content structure is of a property editor, it’s raw value.

That was my original port of call but, as v13 is no longer the main branch, searching GitHub is a nightmare - it was giving results about an IMediaImportService that doesn’t exist, and generally un-navigatable.

Unless you know the codebase inside out, and know exactly which folder to look in, the source often adds more confusion. Ideally we need the documentation to be better maintained to give accurate examples.

True, I just have the Umbraco respository locally, so I can switch branches easily :wink:

Now you have an accurate example for the Media Picker, you could do a PR to the documentation with your example :wink:

“Just” doing a lot of heavy lifting there :wink:

2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.