Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent data binding in invisible asp.net panel

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".

like image 632
Mart Avatar asked Jan 21 '14 14:01

Mart


1 Answers

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(); 
            } 
        } 
    } 
}
like image 71
Etherman Avatar answered Oct 20 '22 01:10

Etherman