问题描述
不显示隐藏的( visible = false
)面板,但是对包含的元素执行数据绑定。为什么这样做?更重要的是,如何避免呢?
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>
如果 SelectedUser
是 null
,则不会呈现面板,但会评估 SelectedUser.Name
并生成错误。
If SelectedUser
is null
, the panel is not rendered but SelectedUser.Name
is evaluated and generates an error.
我显然可以写<%#SelectedUser!= null吗? SelectedUser.Name:%>
,但会增加混乱。
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?
Panel
控件在这里并不重要,它可能是带有 runat = server
的纯HTML元素。
The Panel
control is not important here, it could be a Placeholder of a plain HTML element with runat="server"
.
推荐答案
I可能在这一点上很晚,但我也觉得很烦。
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:
该解决方案是对标准PlaceHolder控件的简单覆盖,以在Visible为false时禁止绑定子控件:
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();
}
}
}
}
这篇关于防止在不可见的ASP.NET面板中进行数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!