How can I make an if statement inside a repeater

<asp:Repeater> driving me crazy ..

I need to do

 <ItemTemplate> <% if (Container.DataItem("property") == "test") {%> I show this HTML <% } else { %> I show this other HTML <% } %> </ItemTemplate> 

But I can’t find a way to do this for me. Ternary is not suitable, because the amount of HTML is quite large, setting labels through the DataBind event is also not very good, since I will have to have large blocks of HTML in the code.

Of course, there is a way to do this ....

+6
c # if-statement repeater
source share
6 answers

You can try to create a ViewModel class, make a decision on your code, and then be happy with your repeater by simply displaying the data that is given to it.

This is a way to separate the logic from the user interface. Then you can have a mute-user interface that simply displays the data, without the need to determine what / how to display.

+7
source share

You can use server side visibility:

 <ItemTemplate> <div runat="server" visible='<% (Container.DataItem("property") == "test") %>'> I show this HTML </div> <div runat="server" visible='<% (Container.DataItem("property") != "test") %>'> I show this other HTML </div> </ItemTemplate> 
+19
source share

You can do this with custom controls:

 <ItemTemplate> <uc:Content1 runat='server' id='content1' visible='<%# Container.DataItem("property") == "test" %>'/> <uc:Content2 runat='server' id='content2' visible='<%# Container.DataItem("property") != "test" %>'/> </ItemTemplate> 
+3
source share

Looks like I got this mix with the actual data binding

You can do it like this:

 <asp:Repeater runat="server"> <ItemTemplate> <% if (((Product)Container.DataItem).Enabled) { %> buy it now! <% } else {%> come back later! <% } %> </ItemTemplate> </asp:Repeater> 

Strike>

+3
source share

I had a similar problem and came across this page. Thanks for the great answers, Gavin and Keltex gave me the right way, but I had a bit of hard time for this to work on my page. In the end, I managed to get him to work with this Boolean, so I wanted to share the descendants:

Show checkbox if false

 <asp:CheckBox ID="chk_FollowUp" Visible='<%# (DataBinder.Eval(Container.DataItem, "FollowUp").ToString() == "False") %>' runat="server" /> 

Show img flag if true

 <asp:Image ID="img_FollowUp" AlternateText="Flagged" ImageUrl="Images/flag.gif" runat="server" Visible='<%# DataBinder.Eval(Container.DataItem, "FollowUp") %>' Height="30" Width="30" /> 
0
source share

First you need to define the Count variable in the Page.cs file

  <%if (Count == 0) { %> <div style="background-color:#cfe9ed" class="wid_100 left special_text"><%# Eval("CompanyName") %></div> <%} else if (Count == TotalCount - 1) { %> <div style="background-color:#f2f1aa" class="wid_100 left special_text"><%# Eval("CompanyName") %></div> <%} else { %> <div class="wid_100 left special_text"><%# Eval("CompanyName") %></div><% } %> <%Count++; %> 
0
source share

All Articles