I have created a folder in Umbraco and I would like to display a random image from that folder on my page.
I found a solution from a few years ago which was giving me compile errors
dynamic folder = Library.MediaById(1054);
var randomImage = folder.Children.Where("nodeTypeAlias = \"Image\"").Random();
I found that I have to add the proper inherits in my file
@using umbraco.MacroEngines
@inherits DynamicNodeContext
but this it gives me an error because I already have a @model I'm using in the first line
The 'inherits' keyword is not allowed when a 'model' keyword is used.
Thanks for any help
You can take a look and learn from sample macro partial views pre-installed in each Umbraco website. There is a snippet called List Images From Media Folder.
The code of the default snippet looks like this:
@inherits Umbraco.Web.Macros.PartialViewMacroPage
@*
Macro to display a series of images from a media folder.
How it works:
- Confirm the macro parameter has been passed in with a value
- Loop through all the media Id's passed in (might be a single item, might be many)
- Display any individual images, as well as any folders of images
Macro Parameters To Create, for this macro to work:
Alias:mediaId Name:Select folder with images Type:Single Media Picker
*@
@{ var mediaId = Model.MacroParameters["mediaId"]; }
@if (mediaId != null)
{
@* Get all the media item associated with the id passed in *@
var media = Umbraco.Media(mediaId);
var selection = media.Children("Image");
if (selection.Any())
{
<ul>
@foreach (var item in selection)
{
<li>
<img src="@item.umbracoFile" alt="@item.Name" />
</li>
}
</ul>
}
}
We need to remember to add the parameter to macro if we're using them there. Then we can use both: Media or TypedMedia helper methods to retrieve folder (which is typical media item with different type), despite of the required returned type. I usually use TypedMedia to be able to operate on strongly typed object and preview properties in Visual Studio.
If we create macro properly and insert it on the template using code like this (with proper folder ID):
@Umbraco.RenderMacro("Test", new { mediaId="1082" })
we should see a list of images from this folder (all of them at that moment).
The final part is almost the same as you previously did it, but we need to adjust it a little bit. My final code and suggestion is below:
@inherits Umbraco.Web.Macros.PartialViewMacroPage
@{
var folderId = Model.MacroParameters["mediaId"];
if (folderId != null)
{
var media = Umbraco.TypedMedia(folderId);
var rand = new Random();
var imagesInFolder = media.Children("Image");
if(imagesInFolder.Any()) {
var pick = imagesInFolder.ElementAt(rand.Next(0, imagesInFolder.Count()));
if (pick != null)
{
<img src="@pick.GetCropUrl()" alt="@pick.Name" />
}
}
}
}
Let me know if it solved your problem :)