Proper way to handle a conditional PlaceHolder in ASP.net
I'm still getting used to the way ASP.net WebForms handles things but this one is still puzzling to me. In some instances I have markup that should be displayed if an object is null and that markup should contain values from t开发者_如何学运维hat object.
A very simple example:
<asp:PlaceHolder runat="server" Visible='<%# myObject != null %>'>
<span><%= myObject.Property %></span>
</asp:PlaceHolder>
The problem is that it seem ASP.net parses the contents of the placeholder regardless of the visibility. The above code ends with the error:
Object reference not set to an instance of an object.
Is there a way to handle this without having a million <asp:Literal>
's?
Set the visibility of the placeholder server side (i.e in your code behind)
example:
this.placeholdername.Visible = true;
if ( myObject == null )
{
this.placeholdername.Visible = false;
}
You can also achieve this by using an inline condition.
<%if (myObject != null) { %>
//Control here
<% } %>
.Net will still parse the child controls regardless of visibility of the parent. So this is expected.
You could certainly use literals or simply make sure an object is created but maybe with a switch that sets whether or not it's displayed.
Another route would be to use a repeater and databind the repeater to your object. If the object's null, then the repeater isn't going to create it's children...
That may work:
<asp:PlaceHolder runat="server">
<span runat="server" Visible='<%# myObject != null %>'><%= myObject.Property %></span>
</asp:PlaceHolder>
精彩评论