views:

19

answers:

2

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?

A: 

Hey,

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....

Brian
@Brian: That would technically work but I'd prefer to render nothing. If only I could use MVC, unfortunately not an option.
Alex Angas
+1  A: 

Hi,

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

keyboardP
@TenaciousImpy: That's a good idea as well. I just wish there was something inline that could be done!
Alex Angas
@Alex - This post has two suggestions that could work:`http://forums.asp.net/p/302270/302270.aspx#302270`. Also, thanks to internet archiving :D, this page has an inline solution `http://web.archive.org/web/20080610160756/http://www.openmymind.net/index.aspx?documentId=8`
keyboardP
@TenaciousImpy: I tried the first link which was OK but then used the inline option from your second link on a label. This is the sort of thing I'm looking for. Perhaps you could put these links as an update to your answer?
Alex Angas