开发者

Control value persistance across postbacks

Given the following code, can an开发者_开发技巧yone explain how on earth the dropdownlist is remembering its selected value across postbacks, given that viewstate is disabled and the control is being constructed after the viewstate has finished tracking values.

DropDownList ddl;
protected void Page_Load(object sender, EventArgs e)
{
    ddl = new DropDownList() {AutoPostBack = true, EnableViewState = false, ViewStateMode = ViewStateMode.Disabled };
    ddl.Items.Add(new ListItem("1"));
    ddl.Items.Add(new ListItem("2"));
    div.Controls.Add(ddl);
}


A control uses ControlState, which is separate from the ViewState. But similar in implementation.

ControlState vs. ViewState


Viewstate is not used to retain the value posted to the server. It may be used to retain the value that was selected the last time it was served to the client in viewstate but this is only so it can generate server side events such as selectedindexchanged. Its current value however is determined by what was posted by the control to the server. DropDownList implements IPostBackDataHandler which "Defines methods that ASP.NET server controls must implement to automatically load postback data."

Again, the current value of the DropDownList is not retrieved from ViewState, it is retrieved from the posted form values. If you do not need it to maintain its value, set its selected index to 0 (or whatever the default index is) after you have added it to the control tree. It is important you do it after you have added otherwise the posted value will be loaded when you add it to the control tree.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜