记录ASP.NET页面表单初始状态(主要是为了前台可以根据这个判断页面是否变动了)
把页面表单状态记录到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(); } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。