Copied to clipboard

Flag this post as spam?

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


  • Bent Holz 100 posts 273 karma points
    Aug 14, 2017 @ 13:32
    Bent Holz
    0

    Simple show/hide if property has value

    I thought this would be "simple"... Being new to Razor/Umbraco 7, I am looking at the Umbraco Razor Cheatsheet (ver. 6?) and trying to make sense of it all... but alas...

    On my frontpage I would like to have a div show if a property from my frontpage doc type has a value:

    @{
        var getInfo = Model.Content.GetPropertyValue("frontpageInfo");
        if (getInfo != null )
        {
            <div class="container" style="color: #fff; background: #f00;">
                @getInfo <p>read more here...</p>
            </div>
        }
    }
    

    The div shows no matter if property has value or not... What am I missing?

  • Nandoh 32 posts 104 karma points
    Aug 14, 2017 @ 14:10
    Nandoh
    1

    Hi and welcome :)

    Did you debug and check the value after GetPropertyValue? I think that your variable will have an empty string set'ed by GetPropertyValue.

    Do the compare like: !String.IsNullOrWhiteSpace([your_variable])

    :)

  • Bjarne Fyrstenborg 1284 posts 4038 karma points MVP 8x c-trib
    Aug 14, 2017 @ 14:14
    Bjarne Fyrstenborg
    100

    Hi Bent

    If you use the checkbox (true/false) property editor, the property will most likely always contains a value (0 or 1 in the published xml cache).

    You can cast the property to a boolean and then compare against true or false, e.g.

    @{
        var getInfo = Model.Content.GetPropertyValue<bool>("frontpageInfo");
        if (getInfo == true)
        {
            <div class="container" style="color: #fff; background: #f00;">
                @getInfo <p>read more here...</p>
            </div>
        }
    }
    

    or if it is a string property cast the property as a string.

    @{
        var getInfo = Model.Content.GetPropertyValue<string>("frontpageInfo");
        if (!string.IsNullOrWhiteSpace(getInfo))
        {
            <div class="container" style="color: #fff; background: #f00;">
                @getInfo <p>read more here...</p>
            </div>
        }
    }
    

    /Bjarne

  • Bent Holz 100 posts 273 karma points
    Aug 14, 2017 @ 14:48
    Bent Holz
    0

    Ok great!... That was a solution...

    So is ther also <int>, <float> etc?

    Cheers!

    /Bent

  • Bjarne Fyrstenborg 1284 posts 4038 karma points MVP 8x c-trib
    Aug 15, 2017 @ 09:46
    Bjarne Fyrstenborg
    1

    Yes, you can also cast to other types like <int>, <float>, <decimal>, <DateTime> etc. and choose the ideal type depending on the datatype you are using.

    /Bjarne

Please Sign in or register to post replies

Write your reply to:

Draft