Morten Holmgaard
Morten Holmgaard

Reputation: 7806

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>

Upvotes: 1

Views: 171

Answers (1)

McGarnagle
McGarnagle

Reputation: 102753

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) %>

Upvotes: 1

Related Questions