Copied to clipboard

Flag this post as spam?

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


  • Jon 38 posts 157 karma points
    Nov 19, 2015 @ 11:49
    Jon
    0

    HasValue in Controller and Best Practice

    I find the inconsistencies between Umbraco's Razor syntax and snytax used in controllers and other back end code frustrating.

    In a Razor view if I want to check to see if a property has a value I do this:

    @if (Model.HasValue("propertyName"))
    {
        // Do stuff
    }
    

    In back end code I do this:

    if (Model.GetProperty("propertyName") != null && Model.GetProperty("propertyName").Value != null)
    {
        // Do stuff
    }
    

    Is this the right way to check to see if a property has a value? Is this too much? What is the best way to check to see if a property has a value?

  • Gary Devenay 39 posts 245 karma points
    Nov 19, 2015 @ 12:09
    Gary Devenay
    0

    You can shorten it slightly by using

    if (Model.GetProperty("propertyName") != null && Model.HasValue("propertyName"))
    {
        // Do stuff
    }
    

    I personally don't think this is too much in the view, as it provides graceful degrading on your views - which means if something unexpected should change you won't be getting YSOD's.

    That being said - doing the check in your controller isn't required, as you're repeating yourself in the view.

  • Jon 38 posts 157 karma points
    Nov 19, 2015 @ 12:21
    Jon
    0

    Hi Gary,

    Thanks for the reply.

    I'm more interested in the best way to do it in the back end. I'm doing some logic that doesn't just involve the 'Model' and draws from other IPublishedContent. I would therefore prefer to keep this logic within a controller.

    Basically I'd like to fact check whether what I'm doing in the back end code is the best way to check whether a property has a value.

    I'm happy with how it's done in the Razor view but HasValue isn't available in the back end code and I want to check best practice.

    Thanks!

  • Jon 38 posts 157 karma points
    Nov 19, 2015 @ 12:36
    Jon
    100

    Adding this reference:

    using Umbraco.Web;
    

    Gives you access to all of the extensions you get in the Razor views.

    Had to poke around in ILSpy to find them. =)

  • Valentin Valev 2 posts 72 karma points
    Apr 01, 2020 @ 23:59
    Valentin Valev
    0

    I am using Umbraco.Web but I got no access to any of these. I am trying so badly to get the value of the backoffice, a value of a label that displays the amount of failed login attempts. However, HasValue is not available anywhere... Any ideas? I tried accessing it by member.GetType().GetProperty("propertyname").GetValue("label name").ToString(); as of Model.HasValue or anything like that at no avail is available. I will appreciate any help.

Please Sign in or register to post replies

Write your reply to:

Draft