Search code examples
c#asp.net-mvccheckboxsitecoreglass-mapper

Handling CheckboxField in GlassMapper


I am currently using Glass Mapper to map items in the sitecore tree to Model classes in C#, however I am having issues when trying to read the Checked parameter of a checkbox field on the item.

How do I read the Checked property? I have tried setting the field below to a CheckboxField data type but it has still failed to load the data I require.

Will I need to create another Model class to extract the CheckboxField template data values?

The class property definition

[SitecoreField("Is Gold Class Package")]
public virtual CheckboxField IsGoldClassPackage { get; set; }

The Razor markup

@foreach (var package in Model.LoyaltyPackages.LoyaltyPackageDataItems)
{
    <div vrewards-item title="@package.Title" unlocked price="@package.Points" icon="@package.Icon"
        @(package.IsGoldClassPackage.Checked == true ? goldClassAttrribute : "") >
    </div>
}

Solution

  • In Glass you don't map the fields but just the values. So your domain model should look like this:

    [SitecoreField("Is Gold Class Package")]
    public virtual bool IsGoldClassPackage { get; set; }
    

    And in your view you can simply get the value from the model:

    @foreach (var package in Model.LoyaltyPackages.LoyaltyPackageDataItems)
    {
        <div vrewards-item title="@package.Title" unlocked price="@package.Points" icon="@package.Icon"
            @(package.IsGoldClassPackage == true ? goldClassAttrribute : "") >
        </div>
    }