提交后控件为空
我的 asp.net 页面上有一个复选框列表和文本框控件,它们是动态创建并添加到页面中的。当我填充值并提交表单时,当它到达服务器时,这些值是空的。有什么帮助吗?
I have a checkboxlist and textbox controls on my asp.net page and the are dynamically created and added to the page. When I populate the values and submit the form, the values are empty by the time it hits the server. Any help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们是空的,因为它们在页面生命周期中重新创建得太晚了。
如果不知道 ASP.NET 页面生命周期中的确切点,您'重新添加控件(尽管我猜它是 Page_Load 或事件处理程序),它是这样的:
(回发)
要解决此问题,您需要确保您的控件在生命周期中尽早创建。标准做法是将“控件创建”分解为一个单独的方法,并在 CreateChildControls 期间检查是否需要创建它们:
这样,如果它们确实需要由生命周期后期的某些东西最初添加,例如事件处理程序(例如 Button_Click),您也可以从那里调用相同的
EnsureDynamicControlsAreAdded
方法,并且在下一次往返时它们将更早创建。They are empty because they are being re-created too late in the page lifecycle.
Without knowing the precise point in the ASP.NET Page Lifecycle you're adding your controls, (though I'd guess it's either Page_Load or an event handler), it goes something like this:
(Postback)
To solve this, you need to make sure your controls are created early enough in the lifecycle. Standard practice is to break the "control creation" into a separate method, and during CreateChildControls, check to see if they need to be created:
This way, if they do need to be initially added by something as far late in the lifecycle as an event handler (Button_Click, for example), you can call the same
EnsureDynamicControlsAreAdded
method from there as well, and on the next round-trip they'll be created much earlier.除了 Rex M 的回答之外,您可以尝试在“
Page_Init
”事件中创建控件 - 这是页面生命周期中的第一个事件之一,也是我通常在无视图页面中创建控件的地方(注意:如果这样做,请不要用“if (!IsPostback)
”包围 Page_Init 处理程序的内容 - 这将阻止其按预期工作)。Further to Rex M's answer, you could try creating the controls in the "
Page_Init
" event - this is one of the first events in the page lifecycle, and is where I would normally create controls in a viewstateless page (NB: If you do this, do not surround the content of the Page_Init handler with an "if (!IsPostback)
" - this will prevent it from working as intended).