回发时输入文本控件消失



我在代码后面以这种方式创建了一些输入控件(文本),作为动态RadiobuttonList的一部分(这样文本框就在单选按钮旁边):

RadioButtonList radioOption = new RadioButtonList();
 radiobuttonlist.Items.Add(new ListItem(dt.Rows[i][9].ToString() + " <input id="" + name + "" runat="server" type="text" value="Enter text" />")

所有的控件都在UpdatePanel内。

每次有回发,输入控件中的文本就会消失。

如何保持输入文本值?

任何想法?感谢!

控件树必须在每次回发上重建,包括部分回发-或者让它通过ControlState/ViewState重建。在这种情况下,在随后的回发中,Items集合不会重新构建(或被清除),并且在Render阶段为空。

对于这种情况,我会这样处理:

  1. 在RadioButtonList 上启用ViewState,确保它的添加不迟于Load1或;
  2. 在容器控件上存储适当集合的ViewState,然后绑定消费控件——参见GenericDataSourceControl,以获得一种干净的方式来设置它。我更喜欢这种方法,因为它是一致的,可预测的,易于控制。

1应该工作,但它可能不工作。我经常感到困惑的是,哪些控件真的支持ViewState,以及在多大程度上使用它总是让我觉得…不一致的。在任何情况下,如果ViewState被禁用,它将无法工作-记住,禁用页面(或父控件)的ViewState将一直禁用ViewState。此外,控件必须在适当的时间以相同的控件路径/ID(通常是Init或Load)加载到控件树中,以便它能够正确地与请求ViewState一起工作。


#2的大致思路:

将视图状态保存在包含用户控件中(必须为该控件启用ViewState):

// ListItem is appropriately serializable and works well for
// automatic binding to various list controls.
List<ListItem> Names {
    // May return null
    get { return (List<ListItem>)ViewState["names"]; }
    set { ViewState["names"] = value; }
}

在genericdatasourceccontrol(将GDS放入标记中,因此它有一个很好的ID)中选择事件:

void SelectEvent(sender e, GenericSelectArgs args) {
   args.SetData(Names);
}

动态添加RadioButtonList(例如,在Control.OnLoad中):

// Unless this NEEDS to be dynamic, move it into the declarative markup.
// The dynamic control must be added to the *same location* it was before the
// postback or there will be ugly invalid control tree creation exceptions.
var radioList = new RadioButtonList();
someControl.Controls.Add(radioList);
// To minimize problem with Control Tree creation this should be unique and
// consistent for dynamic controls.
radioList.ID = "radioList";
// Binding to the DS "declarative" usually works better I've found
radioList.DataSourceID = "idOfTheGDS";
// You -may- need to DataBind, depending upon a few factors - I will usually call
// DataBind in PreRender, but generally in the Load is OK/preferred.
// If it already binds, don't call it manually.
radioList.DataBind();

如果DataBinding工作正常,那么应该可以禁用 ViewState for RadioButtonList ..但有时ViewState在ControlState应该使用的时候使用,所以要确保它的功能是理想的

最新更新