Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Saied 349 posts 674 karma points
    Oct 02, 2015 @ 18:17
    Saied
    0

    Is it possible to optimize this code that gets an image from the Media section?

    I have the following code executing in the head section of my template. It works fine, but I was curious if it could be optimized?

    @{
    
    var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
    
    umbracoHelper.TypedMediaAtRoot().DescendantsOrSelf("Folder").FirstOrDefault(x => x.Name == "Product Images");
    
    var modelFolder = umbracoHelper.TypedMediaAtRoot().DescendantsOrSelf("Folder").FirstOrDefault(x => x.Name == Model.VehicleModel);
    
        if (modelFolder != null)
        {
            var image = modelFolder.Children(x => x.DocumentTypeAlias == "Image").FirstOrDefault();
    
            if (image != null)
            {
                <style>
                    body.filtered-sct-single-product section.product-value {
                        background: url(@image.Url);
                        background-size: cover;
                        background-position: center;
                    }
                </style>
            }
        }
    }
    
  • Nicholas Westby 2054 posts 7100 karma points c-trib
    Oct 02, 2015 @ 20:07
    Nicholas Westby
    0

    You could use properties that are media pickers to pick folders from your content nodes rather than having to search through the entire media tree.

    You could either have the user set those properties (i.e., pick the media folders), or you could use your code to automatically pick those folders, then have your code programmatically set the picker property so next time it doesn't have to scan the entire media tree.

  • Saied 349 posts 674 karma points
    Oct 02, 2015 @ 20:08
    Saied
    0

    Do you have sample code on how I would do that? Thanks

  • Nicholas Westby 2054 posts 7100 karma points c-trib
    Oct 02, 2015 @ 20:13
    Nicholas Westby
    0

    Look at the content service: https://our.umbraco.org/Documentation/Reference/Management/Services/ContentService

    You can get a node by its ID, set a property, then save it with the content service.

    You can use GetPropertyValue on the current IPublishedContent to get the value of the media picker property (which, of course, you will have to add to the appropriate document types).

Please Sign in or register to post replies

Write your reply to:

Draft