Alex Angas
Alex Angas

Reputation: 60027

Displaying data conditionally within a user control

Within an ASP.NET user control I have the line:

<div>Web: <a href="<%# Eval("Web") %>"><%# Eval("Web") %></a></div>

I'd like to change it so this HTML is only rendered if Web has a value.

I've tried wrapping String.IsNullOrEmpty(Eval("Web") as string) in server side script but Eval can only be used inside a "binding" tag.

What is the best way to do this?

Upvotes: 0

Views: 393

Answers (2)

keyboardP
keyboardP

Reputation: 69372

It's a bit of a workaround, but you could have a hidden field in your ItemTemplate tag:

<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("web") %>' />

You could then set the 'runat' attribute of the div to 'server' and give the div an ID.

<div id="divWeb" runat="server" visible="false">Web: <a href="<%# Eval("Web") %>"><%# Eval("Web") %></a></div>

In your code-behind, you check whether or not HiddenField1 is empty. If it's not empty, then set 'divWeb' visible = true.

The downside to this method is that the user could manually change the HiddenField1 value. However, if that's not a problem (security wise), then you could try this method.

Update The code snippet below is from the inline section of this site:

<asp:Repeater id="collectionRepeater" Runat="server">  
     <ItemTemplate>
      <%# DataBinder.Eval(Container.DataItem, "OwnerId") %> - 
      <asp:literal ID="see" Runat="server" 
         Visible='<%# (int)DataBinder.Eval(Container.DataItem, "Pets.Count") > 0 %>'>
         see pets
      </asp:Literal>
      <asp:literal ID="nopets" Runat="server" 
        Visible='<%# (int)DataBinder.Eval(Container.DataItem, "Pets.Count") == 0 %>'>
          no pets
       </asp:Literal>
       <br />
      </ItemTemplate>
    </asp:Repeater>

There are also alternative options in this thread

Upvotes: 1

Brian Mains
Brian Mains

Reputation: 50728

Well, MVC was meant more for that type of logic in the page... typically with web forms everything is done with code-behind... Additionally, would you consider doing something like:

<div style='<%# ((Eval("Web") != null) ? "display" : "none") %>'>Web: <a href="<%# Eval("Web") %>"><%# Eval("Web") %></a></div>

Haven't tried this approach specifically, but I know tertiary (?:) works in this context, and so it seems logical that it could work....

Upvotes: 1

Related Questions