手动绑定中继器中的行,以避免丢失视图状态数据
本文关键字:数据 视图状态 绑定 中继器 | 更新日期: 2023-09-27 17:57:36
我正在处理一个页面,该页面使用中继器来显示自定义控件的列表,每个控件包含两个下拉列表。
单击Add control
按钮后,页面会在中继器上添加一个新行,单击嵌入每个控件中的Delete control
按钮之一会从中继器中删除相关控件。
删除部分似乎可以工作(将NamingController.Visible
设置为false
),但添加部分失败了,因为一旦我添加了新控件,对新repeater.DataBind()
的调用就会丢失所有视图状态数据,从而阻止下拉列表检索回发前的值。
有没有一种方法可以在不调用完整数据绑定的情况下手动将添加的控件绑定到中继器?或者有没有其他方法可以在不丢失数据的情况下添加控件?
这里有一些代码(我只留下了似乎相关的代码,如果你认为我忘记指定了什么,请告诉我):
页面.aspx:
<asp:Button ID="addControl" runat="server" Text="Add control" />
<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_ItemDataBound">
<ItemTemplate>
<uc:CustomControlWithDropDownLists ID="custom" runat="server" />
</ItemTemplate>
</asp:Repeater>
Page.aspx.cs:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
repeater.DataSource = GetDataSource();
repeater.DataBind();
}
protected void Page_Init(object sender, EventArgs e)
{
addControl.Click += (sndr, args) =>
{
// Create the object we want to bind to the repeater
ObjectToBind objectToBind = new ObjectToBind();
// Here is what causes data loss
((IList<ObjectToBind>)repeater.DataSource).Add(objectToBind);
repeater.DataBind();
};
}
protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Do some stuff
}
}
CustomControlWithDropDownLists.ascx:
<%-- Some dropdown lists --%>
<asp:Button ID="deleteControl" runat="server" Text="Delete control" />
CustomControlWithDropDownLists.ascx.cs:
protected void Page_Init(object sender, EventArgs e)
{
deleteControl.Click += (sndr, args) =>
{
// ... Delete the control ...
((Button)sndr).NamingContainer.Visible = false;
};
}
由于视图状态,您正在丢失数据。当我们重定向到另一个页面时,查看状态会丢失数据。视图状态仅存储特定页面的数据。转到另一个页面时,视图状态会丢失数据。&由于多种原因,在同一页面上丢失数据的可能性很大。因此,存储数据的最佳方式是使用会话变量。会话存储数据,即使您正在重定向到另一个页面。这是存储数据的最佳方式。
默认情况下,它会将数据存储20分钟。
我希望这能解决你的问题。
我过去也做过类似的事情,发现这个来自c-sharp角的链接很有用。http://www.c-sharpcorner.com/Blogs/10913/add-dynamic-row-using-repeater.aspx
如果内存服务器正在使用ViewState对象并相应地进行绑定,则对我来说是关键元素。
myObject=ViewState["MyData"];等
(很抱歉,我现在无法访问我的代码)