Search code examples
razorfilterumbraco

Umbraco & Razor. Filter selection by dropdown value


I have a selection generated from the children of the current page. Within that selection (let's call it Fruit) I have items and each item has a fruitType.

This code doesn't work:

@{
    var selection = CurrentPage.Children("fruit").Where("Visible");
}
<ul>
    @foreach(var item in selection){
        @if(@item.fruitType == "Apple"){
        <li>
            <a href="@item.Url">@item.Name</a><br/>
            @item.fruitName<br>
            @item.fruitType<br>
            @if (item.image != null && !(item.image is Umbraco.Core.Dynamics.DynamicNull))
                        { var m = Umbraco.Media(item.image);
                            <img src="@m.Url" alt="Picture of @item.Name" />
                        }
        </li>
        }
    }
</ul>

What I'm trying to do is to only list the items with a fruitType of "Apple". This value is selected from a "fruitType" dropdown list and I've tried using both the numeric and string values that Umbraco uses from Dropdown datatypes.

It all works perfectly if I remove the if conditional except that it displays all fruit types.

Any suggestions?


Solution

  • sigh Just one too many declarations..

    Turns out neither the if nor the item references need the additional @ declaration in front of it so the correct code looks like:

    @{
        var selection = CurrentPage.Children("fruit").Where("Visible");
    }
    <ul>
        @foreach(var item in selection){
            if(item.fruitType == "Apple"){
            <li>
                <a href="@item.Url">@item.Name</a><br/>
                @item.fruitName<br>
                @item.fruitType<br>
                @if (item.image != null && !(item.image is Umbraco.Core.Dynamics.DynamicNull))
                            { var m = Umbraco.Media(item.image);
                                <img src="@m.Url" alt="Picture of @item.Name" />
                            }
            </li>
            }
        }
    </ul>