ASP.NET 在回发时添加控件

ASP.NET Add Control on postback(ASP.NET 在回发时添加控件)
本文介绍了ASP.NET 在回发时添加控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我整理了一个简单的表单来突出动态表单的概念.我需要做的是在用户单击添加"按钮时向页面添加一个控件.

I've put together a simple form to highlight the concepts of dynamic forms. What I need to do is add a control to the page when the user clicks the "Add" button.

我现在有一个简单的计数器来存储创建的控件的数量,当单击按钮时它会增加.

I have a simple counter at the moment that stores the amount of controls created, which is incremented when the button is clicked.

起初我以为它就像在事件处理程序上调用 RecreateChildControls(类继承自 CompositeControl)一样简单.这确实会根据增加的值创建新控件,但所有控件状态都会丢失.我假设这是因为事件在 Init &加载阶段.

At first I thought it would be as simple as calling RecreateChildControls (the class inherits from CompositeControl) on the event handler. This does create the new controls based on the incremented value, but all the control state is lost. I'm assuming this is because the event has been fired after the Init & Load phase.

还有其他方法可以做到这一点吗?我可以通过检查 Init 事件的回发值来使其工作,但这似乎有点 hacky.

Is there any other way to do this? I can get it to work by inspecting the postback value on the Init event, however this seems to be a little hacky.

推荐答案

这确实会根据增加的值创建新控件,但所有控件状态都会丢失.

This does create the new controls based on the incremented value, but all the control state is lost.

您在 页面生命周期.状态应用于加载"阶段的控件,因此如果控件未在该阶段之前创建,则状态将不会恢复,因为当它尝试时控件不存在应用状态.

You're calling the function too late in the page life cycle. State is applied to your controls for the "Load" stage, and so if the controls are not created before that stage the state won't be restored, because the controls don't exist when it tries to apply the state.

您需要在 Page 的 Init 事件中创建控件.

You need to create the controls in the Page's Init event.

就我个人而言,我不喜欢 ASP.Net 中的动态控件.它们有自己的位置,但更多时候我会选择一个合适的最大允许控件数量,最初将它们全部放在页面上,然后仅根据需要启用/禁用/隐藏/显示它们.

Personally, I'm not a fan of dynamic controls in ASP.Net. They have their place, but more often I choose a suitable maximum number of allowed controls, put them all on the page initially, and only enable/disable/hide/show them as needed.

这篇关于ASP.NET 在回发时添加控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
how do i pass parameters to aspnet reportviewer(如何将参数传递给aspnet report查看器)
Bind multiple parameters from route and body to a model in ASP.NET Core(在ASP.NET Core中将路由和主体中的多个参数绑定到一个模型)
Custom model binding in AspNet Core WebApi?(AspNet Core WebApi中的自定义模型绑定?)
How to minify in .net core mvc view?(如何在.Net核心MVC视图中缩小?)