【问题标题】:ASP Gridview Failed to load viewstate.ASP Gridview 无法加载视图状态。
【发布时间】:2013-10-14 11:14:58
【问题描述】:

当我在 GridView.ROWDATABOUND 事件中动态创建按钮时,我在 asp.net 4.5 中遇到错误。

按钮代码:

Dim btn1 As New Button()
btn1.ID = "btn1"
btn1.Width = "50"
btn1.Text = "Edit"
btn1.CssClass = "AdminPageBtn"
btn1.CommandName = "Edit"
btn1.CommandArgument = "Edit"
btn1.Enabled = True

e.Row.Cells(e.Row.Cells.Count - 1).Controls.Add(btn1)

我也在使用 AJAX 4.0,带有脚本管理器和更新面板。

那个按钮执行下面的方法

Protected Sub gvwRoutes_RowEditing(ByVal sender As Object, 
                      ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)
                Handles gvwRoutes.RowEditing
End Sub

执行时出现错误:

Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

需要一个解决方案..!

【问题讨论】:

  • 尝试将此按钮放入标记中。
  • 那会破坏结构。这在以前的版本中有效,该版本既没有 ajax 也没有更新面板。现在它变成了垃圾,我不知道为什么或做什么
  • 你刚刚说的是anwnsear。不幸的是,更新面板有很多问题,其中之一就是查看状态管理。必须在 Page_OnInit 中创建每个控件才能获得成功!
  • 如何在页面 oninit 中为 gridview 创建按钮?我很好,很难

标签: c# asp.net ajax vb.net gridview


【解决方案1】:

如果您尝试将控件添加到控件集合的中间位置,那么您肯定会遇到视图状态问题。根据 Asp.net 中动态控件的 MSDN specification

Inserting a dynamic control somewhere other than the end of the Controls collection 
can cause a corrupted view state

因此,可能的解决方案是在您的页面中使用Placeholder,您可以在其中添加动态控件。这将在 Control 集合的中间保留索引,并同时处理 View 状态。由于新添加的控件将具有来自占位符控件的视图状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多