ASP.Net: Conditional Logic in a ListView's ItemTemplate

前端 未结 4 1391
别跟我提以往
别跟我提以往 2020-12-15 17:29

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 a

相关标签:
4条回答
  • 2020-12-15 17:59

    If you have 2 different structure that are to be rendered according to a condition then use panels

    <asp:ListView ID="MusicList" runat="server">
        <ItemTemplate>
            <tr>
                <asp:Panel ID="DownloadNull" runat="server" Visible="<%# Eval("DownloadLink") == null %>" >
                <td> Album Description BlaBlaBla <img src="../images/test.gif"> </td>
                </asp:Panel>
    
                <asp:Panel ID="DownloadNotNull" runat="server" Visible="<%# Eval("DownloadLink") != null %>" >
                <td> Album Description BlaBlaBla <img src="../images/test.gif">
                    <a href='<%# Eval("DownloadLink")' >Download</a>
                    ..... 
                </td>
                </asp:Panel>
            </tr>
        </ItemTemplate>
    </asp:ListView>
    
    0 讨论(0)
  • 2020-12-15 18:15

    To resolve "The server tag is not well formed." for the answers involving visibility, remove quotes from the Visible= parameter.

    So it will become:

    <tr runat="server" Visible=<%# Eval("DownloadLink") != null ? true : false %>>
    
    0 讨论(0)
  • 2020-12-15 18:17

    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 %>'>
            <td>
                <a href='<%#Eval("DownloadLink") %>'>Link</a>
            </td>
        </tr>
       </ItemTemplate>
    </asp:ListView>
    
    0 讨论(0)
  • 2020-12-15 18:19

    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.

    0 讨论(0)
提交回复
热议问题