Copied to clipboard

Flag this post as spam?

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


  • Ayo Adesina 445 posts 1059 karma points
    Sep 25, 2014 @ 10:57
    Ayo Adesina
    0

    How to handle Node.GetProperty("name").value when there is no value

    Hey guys I have an umbraco razor view that gets and displays an image, if there is no image i.e the umbraco user has not uploaded one, I don't want to page to crash, I want ignore that fact and load the rest of the page.

    At the moment I am doing this with a try catch block, but I know there must be a much better way to do this.

    @inherits

    Umbraco.Web.Mvc.UmbracoTemplatePage

    @{

    Layout = "umbLayout.cshtml";
    
    bool hasMainImage = true;
    
    try
    {
        var currentPageNode = uQuery.GetCurrentNode();
        var mediaItemId = currentPageNode.GetProperty("mainImage").Value;
    }
    catch (Exception ex )
    {
    
        hasMainImage = false;
    }
    

    } With out the try block it will crash on currentPageNode.GetProperty("mainImage").Value;

  • Dan Lister 416 posts 1974 karma points c-trib
    Sep 25, 2014 @ 11:00
    Dan Lister
    1

    Hi Ayo,

    You could use the following to see if the property has value first:

    if (currentPageNode.HasProperty("mainImage") && currentPageNode.GetProperty("mainImage").Value != null)
    {
        var mediaItemId = currentPageNode.GetProperty("mainImage").Value;
    }
    

    Thanks, Dan.

  • Ayo Adesina 445 posts 1059 karma points
    Sep 25, 2014 @ 11:08
    Ayo Adesina
    0

    Thanks dan! Thats the kind of thing I was looking for having try catch is just unnecessary.

  • Ayo Adesina 445 posts 1059 karma points
    Sep 25, 2014 @ 11:23
    Ayo Adesina
    0

    Dan.... Its actually still crashing ................. Object reference not set to an instance of an object. it does not like currentPageNode.GetProperty("mainImage").Value when it has no value....

Please Sign in or register to post replies

Write your reply to:

Draft