簡體   English   中英

輸入文本控件在回發時消失

[英]Input text control disappears on postback

我以這種方式在代碼的后面創建了一些輸入控件(文本),作為動態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中。

每次回發時,Input控件中的文本都會消失。

如何保留輸入的文本值?

有任何想法嗎? 非常感激!

必須在每個回發(包括部分回發)上重建控制樹,或者讓它通過ControlState / ViewState進行重建。 在這種情況下,在后續的回發中,Items集合不會重建(或清除),並且在Render階段為空。

對於這種情況,我將其視為:

  1. 在RadioButtonList上啟用ViewState 確保不遲於Load 1添加它,或者;
  2. 將適當Collection的ViewState存儲在容器控件上,然后將使用控件的DataBind存儲-請參閱GenericDataSourceControl以獲取一種干凈的方法來進行設置。 我更喜歡這種方法,因為它是一致的,可預測的且易於控制的。

1應該起作用,但可能不起作用。 我通常對哪個控件真正支持ViewState以及使用的程度總是感到困惑感到困惑。 無論如何,如果禁用了ViewState,它將無法正常工作-請記住,禁用頁面(或父控件)的ViewState會完全禁用ViewState。 另外,控制必須在適當的時間使用相同的控制路徑/ ID(通常初始化或負載),以便它將正確地與請求的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; }
}

在GenericDataSourceControl中(將GDS放入標記中,使其具有一個不錯的ID),選擇Event:

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工作正常,則應該可以為RadioButtonList .. 禁用 ViewState,但是有時應該在應該使用ControlState的情況下使用ViewState,因此請確保其正常運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM