I'm attempting to use Sitecore's Field.HasValue
property in Razor syntax to test a particular field, but no matter what I try, the field always seems to be false.
Here's what I'm trying:
@{
var phoneNumber = "";
var numberField = Model.Item.Fields["Header Number"];
if (numberField != null && numberField.HasValue)
{
phoneNumber = numberField.Value;
}
}
As you can see in the screenshot below:
numberField
is being correctly set to a Sitecore FieldnumberField.HasValue
is reporting false
numberField.Value
is (correctly) returning the value of the fieldif
block, phoneNumber
is never set:Is this a bug? Am I using HasValue
incorrectly or is there another Sitecore method I should be using to safely test if fields have a value?
Most probably value of this field comes from the Standard Values item (is inherited).
HasValue
property only returns true when the value is set on the item itself.
Here is the implementation of HasValue
property:
public bool HasValue
{
get
{
return this.GetValue(false, false) != null;
}
}
public string GetValue(bool allowStandardValue, bool allowDefaultValue)
{
...
}
You can check ContainsStandardValue
property to check if the value comes from the Standard Values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With