.net - 如何在 Visible false 的页面加载时停止 UC 的执行

标签 .net asp.net .net-4.0

如果容器页面上的 UC 设置为 Visible false,我正在考虑停止页面加载的执行。现在我遵循以下逻辑

public class TestControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (this.Visible)
        {
            //do heavy operation

        }
    }
}

即我会检查该控件在UC的页面加载中是否可见,如果为true,则只在那里进行操作。还有其他更好的方法吗?我的申请中有很多 UC。如果Visible false,是否有一些通用逻辑来停止UC页面加载的执行。

最佳答案

Control 类的 Visible 属性仅确定是否呈现 Control,但它对控件生命周期的其余部分没有影响。

来自MSDN :

If this property is false, the server control is not rendered. You should take this into account when organizing the layout of your page. If a container control is not rendered, any controls that it contains will not be rendered even if you set the Visible property of an individual control to true. [...]

这是有道理的,因为这样您就可以拥有仍然执行特定操作的不可见控件。您也可以通过不向其中放入任何内容来做到这一点,但它们可能仍然会呈现一些空格或换行符。将 Visible 设置为 false 是最简洁的方法。

如果控件不可见,我认为没有更好的方法来阻止代码的执行,但我认为您的解决方案足够干净。

作为替代方案,您可以将代码放入 OnPreRender 事件中,该事件仅在控件可见时触发。但请记住,这是 Control Lifecycle 中的后续步骤。 .

public class TestControl : System.Web.UI.UserControl
{
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        // Your code here
    }
}

关于.net - 如何在 Visible false 的页面加载时停止 UC 的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371417/

相关文章:

.net - 如何使用 .NET 打开文件以进行非独占写入访问

Javascript,循环通过 gridview 检查隐藏值

c# - 查找数据库中打开的连接数

asp.net - 如何将图像插入电子邮件模板

wpf - 用户控件中的资源字典

c# - 按字符拆分字符串

.net - .NET 程序集上的 AppLocker DLL 规则

asp.net - 你能从请求变量中确定时区吗?

c# - 应用程序错误 System.InvalidOperationException : An unspecified error occurred on the render thread

wpf - VisualStateManager同时出现在WPF Toolkit和PresentationFramework中 - 如何解决