Join our community!

Get everything you need to start developing EPiServer solutions.
November 28 2011, 15:53

Only write to page if property != null, in a PageList

Hi all!

I have a PageList and it lists propertys from child pages, like this.

<itemTemplate>
<%# Container.CurrentPage["EventDate"] %>
</itemTemplate>

Now, if the editor havent written anything in the property on the child's page type I dont want it to be written on the page. So, I tried

<% if (Container.CurrentPage["EventDate"] != null) { %>
      <%# Container.CurrentPage["EventDate"] %>
<% } %>

But that doesnt work. Neither does (because it is always null)

<% if (CurrentPage["EventDate"] != null) { %>
      <%# Container.CurrentPage["EventDate"] %>
<% } %>


How do I solve it? And please, as easy as possible! =) Thank you very much.


  • November 28 2011, 17:19

    The intel says that 'System.ComponentModel.Container' will bind it, but it doesnt work!

  • November 29 2011, 0:11

    Maybe something like this:

    <%# Container.CurrentPage["EventDate"] != null ? ((DateTime)Container.CurrentPage["EventDate"]).ToString() : string.Empty%>

  • November 29 2011, 8:20

    Johan: many many thanks. However that code gave some casting error. But I tried this and it worked:

    <%# Container.CurrentPage["EventDate"] != null ? (Container.CurrentPage["EventDate"]).ToString() : string.Empty %>


    Can you also write this?

    <%# Container.CurrentPage["EventDate"] != null ? (Container.CurrentPage["EventDate"]) : null %>

     

    There is however a little caveat. You see the code is like this really:

    <itemTemplate>
    <h3 style="...">
    <%# Container.CurrentPage["EventDate"] %>
    </h3>
    </itemTemplate>

    So, if I also want to get rid of the h3? But you solution will certenly work, and Iam very gratefull. Thanks.

  • November 29 2011, 8:27

    Ah! You can do like this:

    <%# Container.CurrentPage["EventDate"] != null ? ("<htmlCode>"+Container.CurrentPage["EventDate"]).ToString() : string.Empty%>

  • November 29 2011, 9:01

    I just assumed EventDate was a DateTime-property... If it's just a short string:

    <%# Container.CurrentPage["EventDate"] != null ? "<htmlCode>" + Container.CurrentPage["EventDate"].ToString() + "</htmlCode>" : string.Empty%>

    Or use a PlaceHolder if you need your HTML more readable and not inside code blocks:

    <asp:PlaceHolder runat="server" Visible='<%# Container.CurrentPage["EventDate"] != null%>'>

      <h3 style="...">
        <%# Container.CurrentPage["EventDate"] %>
      </h3>

    </asp:PlaceHolder>

  • November 29 2011, 9:58

    Johan: Thank you!! Awesome. Splendid. So helpful. Have a superb day.