【发布时间】:2010-06-30 08:05:01
【问题描述】:
我有一个关于 asp.net 生命周期层次结构的问题。
基本上,我有一个用户控件,其中包含一个 GridView。而这个 GridView 是基于控件上的一个公共属性(在下面的简化代码中名为 Parameter)动态生成的。
当我将此控件插入到 aspx 页面中,设置其 Parameter 属性并在其上调用 DataBind(Parameter) 时,一切都很好。 GridView 在 UI 上生成和填充。
回发页面时出现问题。我必须重新生成 GridView 结构,以便控件的 ViewState 中的数据可以用于填充 GridView。这样我才能实现它的内容。但只要 GridView 结构是动态生成的,并且是基于其上设置的 Parameter 属性,这是不可能的。因为用户控件的 OnInit 在页面的 OnInit 之前被调用,这就是为什么在 GridView 结构生成之后设置 Parameter 属性的原因。结果我最后得到了一个空的 Gridview。
这里是简化的代码。
你能给我一些建议如何克服这个问题吗?
我可以显式强制 asp.NET 重新加载 gridview 的 ViewState 吗?
页面 HomePage.aspx 有一个 OnInit 事件处理程序,它设置 属性 用户控件ctlMyUSerControl
protected override void OnInit(EventArgs e)
{
ctlMyUserControl.Parameter = new Parameter()
name="Orhan",
surname= "Pamuk"};
}
在 ctlMyUserControl 的 OnInit 我有
protected override void OnInit(EventArgs e)
{
if (Page.IsPostBack && Parameter !=null && SomeGridViewRowsExistOnUI)
{
// Generate dynamic columns based on Parameter property
// So that gridview can be populated
// with the post-backed data which
// should contain the ViewState of the gridview
GenerateGridViewColumns(Parameter);
}
base.OnInit(e);
}
【问题讨论】:
标签: asp.net gridview viewstate page-lifecycle loadviewstate