A hidden (visible="false"
) panel is not rendered, but data binding is executed on contained elements. Why is that done? And more important, how to avoid it?
Here is an example where it is annoying:
<asp:Panel ID="UserPanel" runat="server" visible="<%# SelectedUser != null %>">
<%# SelectedUser.Name %>
</asp:Panel>
If SelectedUser
is null
, the panel is not rendered but SelectedUser.Name
is evaluated and generates an error.
I could obviously write <%# SelectedUser != null ? SelectedUser.Name : "" %>
but it adds clutter.
Is there a way to simply and elegantly prevent data binding within a panel when I know it is not needed?
The Panel
control is not important here, it could be a Placeholder of a plain HTML element with runat="server"
.
I may be late on this one but I also find this very annoying.
I need this often if I am rendering a list of items where each item may be a different class - in which case the properties in the data binding expressions will give errors in the invisible sections intended for other class types. You'll know if you want this.
The best solution I have found is described here:
http://hermanussen.eu/sitecore/wordpress/2011/04/prevent-nullrefs-when-databinding-with-placeholders/
The solution is a simple override of the standard PlaceHolder control to suppress binding child controls if Visible is false:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
namespace Website.Controls
{
public class DataPlaceHolder : PlaceHolder
{
protected override void DataBindChildren()
{
if (Visible)
{
base.DataBindChildren();
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With