views:

3029

answers:

2

I want to show certain parts of an ItemTemplate based according to whether a bound field is null. Take for example the following code:

(Code such as LayoutTemplate have been removed for brevity)

<asp:ListView ID="MusicList" runat="server">
    <ItemTemplate>
        <tr>
            <%
                if (Eval("DownloadLink") != null)
                {
            %>
            <td>
                <a href="<%#Eval("DownloadLink") %>">Link</a>
            </td>
            <%
                } %>
        </tr>
    </ItemTemplate>
</asp:ListView>

The above gives the following run-time error:

Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

So how can put some conditional logic (like the above) in an ItemTemplate ?

+2  A: 

Hi,

What about binding the "Visible" property of a control to your condition? Something like:

<asp:ListView ID="MusicList" runat="server">
<ItemTemplate>
    <tr runat="server" Visible='<%# Eval("DownloadLink") != null ? true : false %>'>
        <td>
            <a href="<%#Eval("DownloadLink") %>">Link</a>
        </td>
    </tr>
</ItemTemplate>

Neil Fenwick
Hmm interesting point...but isn't there some way of injecting logic blocks in the ItemTemplate?
Andreas Grech
modified your answer to return a bool instead of string
Andreas Grech
Hi, thanks for changing the bool - I hadn't tested it, just a quick bit of code to give you the idea.The only way that I know to do what you want to do "properly" is using a framework like MVC, where inline code is the norm in your Views.I don't think the ASP.NET web-forms model lends itself to inline conditional logic in the template. Its not really processed like a script so much as a template with a code-behind.Sorry couldn't be more help
Neil Fenwick
+1  A: 

I'm not recommending this as a good approach but you can work around this issue by capturing the current item in the OnItemDataBound event, storing it in a public property or field and then using that in your conditional logic.

For example:

<asp:ListView ID="MusicList" OnItemDataBound="Item_DataBound" runat="server">
    <ItemTemplate>
        <tr>
            <%
                if (CurrentItem.DownloadLink != null)
                {
            %>
            <td>
                <a href="<%#Eval("DownloadLink") %>">Link</a>
            </td>
            <%
                } %>
        </tr>
    </ItemTemplate>
</asp:ListView>

And on the server side add the following code to your code behind file:

public MusicItem CurrentItem { get; private set;}

protected void Item_DataBound(object sender, RepeaterItemEventArgs e)
{
   CurrentItem = (MusicItem) e.Item.DataItem;
}

Note that this trick will not work in an UpdatePanel control.

MikeD