ASP.NET Add Control on postback(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 在回发时添加控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ASP.NET 在回发时添加控件
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01