提交后控件为空

发布于 2024-08-07 23:02:52 字数 87 浏览 6 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何止钟意 2024-08-14 23:02:52

它们是空的,因为它们在页面生命周期中重新创建得太晚了。

如果不知道 ASP.NET 页面生命周期中的确切点,您'重新添加控件(尽管我猜它是 Page_Load 或事件处理程序),它是这样的:

  • 构建控制树
  • 添加动态控件
  • 渲染

(回发)

  • 构建控制树
  • 重构视图状态 & 重新添加控件绑定到 Post 值
  • 添加动态控件
  • 渲染

要解决此问题,您需要确保您的控件在生命周期中尽早创建。标准做法是将“控件创建”分解为一个单独的方法,并在 CreateChildControls 期间检查是否需要创建它们:

override CreateChildControls()
{
    if(IsPostBack)
    {
        EnsureDynamicControlsAreAdded();
    }
}

这样,如果它们确实需要由生命周期后期的某些东西最初添加,例如事件处理程序(例如 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:

  • Build control tree
  • Add dynamic controls
  • Render

(Postback)

  • Build control tree
  • Reconstitute viewstate & bind to Post values
  • Add dynamic controls
  • Render

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:

override CreateChildControls()
{
    if(IsPostBack)
    {
        EnsureDynamicControlsAreAdded();
    }
}

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.

蓝天 2024-08-14 23:02:52

除了 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文