Copied to clipboard

Flag this post as spam?

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


  • blackhawk 313 posts 1368 karma points
    Jan 24, 2018 @ 21:24
    blackhawk
    0

    Check if media exist in razor

    I have the following logic I am using to load a favicon in my master template...

      @{
            @*load favicon | add a condition to detect if typemedia exist*@
            var mfavicon = Umbraco.TypedMedia(1284).Url;
            <link rel="icon" type="image/png" href="@mfavicon">
        }
    

    Is there a strong type way in wrapping this into a condition that checks if 1284 exist, then execute?

    Thanks

  • Anders Bjerner 487 posts 2990 karma points MVP 8x admin c-trib
    Jan 24, 2018 @ 21:47
    Anders Bjerner
    1

    The method TypedMedia will return an instance of IPublishedContent - you can check whether this is null like this:

    IPublishedContent mfavicon = Umbraco.TypedMedia(1284);
    
    if (mfavicon != null) {
        <link rel="icon" type="image/png" href="@mfavicon.Url">
    }
    
  • Nik 1614 posts 7260 karma points MVP 7x c-trib
    Jan 24, 2018 @ 21:48
    Nik
    1

    Hi Blackhawk,

    I "think" you can do a null check on what is returned from TypedMedia. If the id doesn't exist then I believe it returns null.

    Personally, if I was taking that approach on the Home node (your site's root node). I would have a media picker to pick the media item to use. Then get the value from there. It is bad practice to hard code content/media id's as it is possible for them to be deleted.

    You'd possibly also want some logic to check that the media item actually still exists on the disk. This is a nice little blog post on how to do that: https://codeshare.co.uk/blog/how-to-get-the-file-path-of-a-media-item-in-umbraco/

    Thanks,

    Nik

  • blackhawk 313 posts 1368 karma points
    Jan 25, 2018 @ 02:52
    blackhawk
    0

    Thanks for the tip on leveraging media picker rather than hard coding Id's. Much appreciated on that insight! I'm gonna give this approach a shot.

Please Sign in or register to post replies

Write your reply to:

Draft