把页面表单状态记录到HiddenField中.
这里只提供后台代码, 前台逻辑根据需求*定义.
存放值的ViewState:
protected Dictionary<string, string> HiddenFieldForOriginal { get { var data = ViewState["HiddenFieldForOriginal"]; if (data == null) { Dictionary<string, string> ndata = new Dictionary<string, string>(); ViewState["HiddenFieldForOriginal"] = ndata; } return (Dictionary<string, string>)ViewState["HiddenFieldForOriginal"]; } }
记录表单原始值:
protected void SaveOriginalData(Control control, bool childVisible) { if (control != null) { if (control.HasControls()) //有子控件, 往下遍历. { foreach (Control item in control.Controls) { if (control.Parent.Visible) { SaveOriginalData(item, control.Visible); } else { ////这里逻辑是: 父控件是隐藏的, 子控件也就不记录了. SaveOriginalData(item, control.Parent.Visible); } } } else { string name = control.GetType().Name; string id = control.ClientID + "HiddenField"; if (name == "TextBox" || name == "DropDownList" || name == "CheckBox" || name == "RadioButton") { if (childVisible) { if (!HiddenFieldForOriginal.Keys.Contains(id)) { switch (name) { case "TextBox": HiddenFieldForOriginal.Add(id, ((TextBox)control).Text); break; case "DropDownList": HiddenFieldForOriginal.Add(id, ((DropDownList)control).SelectedValue); break; case "CheckBox": HiddenFieldForOriginal.Add(id, ((CheckBox)control).Checked ? "1" : ""); break; case "RadioButton": HiddenFieldForOriginal.Add(id, ((RadioButton)control).Checked ? "1" : ""); break; default: break; } } } else { if (HiddenFieldForOriginal.Keys.Contains(id)) HiddenFieldForOriginal.Remove(id); } } } } }
以下代码可以放在渲染前事件里面:
Panel defaultPanel = defaultUpdatePanel.FindControl("DefaultPanel") as Panel; if (defaultPanel != null) { SaveOriginalData(defaultPanel, defaultPanel.Visible); foreach (var c in HiddenFieldForOriginal) { if (!string.IsNullOrEmpty(c.Key)) { HiddenField hiddenField = null; try { hiddenField = new HiddenField(); hiddenField.ID = c.Key; hiddenField.ClientIDMode = System.Web.UI.ClientIDMode.Static; hiddenField.ViewStateMode = System.Web.UI.ViewStateMode.Disabled; hiddenField.Value = c.Value; defaultPanel.Controls.Add(hiddenField); } finally { if (hiddenField != null) hiddenField.Dispose(); } } } }