Search code examples
asp.netvisibilityasp.net-4.5asp.net-placeholder

Why is the content inside the invisible asp:PlaceHolder rendered?


Why is the content inside the placeholder rendered? This code results in: "Object reference not set to an instance of an object." For the MainGuard object!

How should one handle this situation?

<asp:PlaceHolder runat="server" Visible="<%# Model.MainGuard != null %>">
    <asp:Image runat="server" ImageUrl="<%# Model.MainGuard.Image.RenderImage() %>" Height="50" />
    <%# Model.MainGuard.Name %>
</asp:PlaceHolder>

Solution

  • It's not rendered -- but it still has to be parsed by the runtime, hence you still get the exception. Your only recourse is to check for null each time:

    <asp:Image runat="server"
        ImageUrl="<%# Model.MainGuard == null ? "" : Model.MainGuard.Image.RenderImage() %>" />
    <%# Model.MainGuard == null ? "" : Model.MainGuard.Name %>
    

    You might consider using an extension method to allow for cleaner syntax:

    public static string StringOrEmpty(this MyClass self, Func<MyClass, string> selector)
    {
        if (self == null) return "";
    
        return selector(self);
    }
    

    Then you can write:

    <asp:Image runat="server"
        ImageUrl="<%# Model.MainGuard.StringOrEmpty(mainGuard => mainGuard.Image.RenderImage()) %>" />
    <%# Model.MainGuard.StringOrEmpty(mainGuard => mainGuard.Name) %>