Conditional logic in ListView ItemTemplate with DataBinder.Eval


Embarrasingly simple, but something I always seem to forget, and then never blog! I needed to show a tick in a repeater when a row value was -1: Simple! In MVC, with the razor syntax and strongly typed views I’ve grown to love, this is a pinch o’ the proverbial piss- In WebForms rreviously I often resort to setting up an ItemDataBound event handler which hides or shows an image, but to be honest I could not be bothered- this seems such overkill for something as simple as this. Anyway, after some faffing I reminded myself the easiest method is to use an ‘in-line if’ in the ItemTemplate, like so;

<ItemTemplate>
        <tr>
            <td><%# Eval("CarReg") %></td>
            ...
            <td>
                <%# (DataBinder.Eval(Container.DataItem, "NewRepeat") != null && DataBinder.Eval(Container.DataItem, "NewRepeat").Equals(-1) ? "<img src=\"../images/tick.png\" alt=\"tick\" />" : "<img src=\"../images/cross.png\" alt=\"cross\" /")%>
            </td>
  1. No comments yet.
(will not be published)