我已经创建了树视图的用户控件。我需要在页面的回发中保持他的状态。为了维护树视图的状态,我使用了会话,但是我使用了out proc会话管理,并且由于这个树视图会话对象无法序列化。有没有其他方法来维护树视图的状态。这是代码
<asp:TreeView Height="100%" ID="MyTreeView" OnTreeNodeCollapsed="MyTreeView_TreeNodeCollapsed" OnTreeNodeExpanded="MyTreeView_TreeNodeExpanded" />
protected void MyTreeView_TreeNodeCollapsed(object sender, EventArgs e)
{
if (!IsPostBack) return;
state = new TreeViewState("TreeViewState");
state.SaveTreeView(MyTreeView, "TreeViewState", HttpContext.Current);
}
protected void MyTreeView_TreeNodeExpanded(object sender, EventArgs e)
{
if (!IsPostBack) return;
state = new TreeViewState("TreeViewState");
state.SaveTreeView(MyTreeView, "TreeViewState", HttpContext.Current);
}
上述方法来自http://code.msdn.microsoft.com/CSASPNETMaintainTreeViewSta-c7673683
答案 0 :(得分:1)
我的母版页上有一个TreeView,我将状态保存在cookie中,因此导航到不同的页面并不总是折叠导航树。
在母版页中,我会在卸载页面之前存储树的状态:
<script type="text/javascript" language="javascript">
window.onbeforeunload = function () {
try {
// The expanded state of the treeview is available in the hidden input
// ..._ExpandState. Store that string in a cookie so we have it on the server
// side when the page is loaded in order to restore the state of the treeview.
var expInfo = document.getElementById('<%=TreeView1.ClientID%>' + '_ExpandState');
if (expInfo)
{
createCookie('ToolsTVExpand', expInfo.value, 365);
}
}
catch (err) {
// Ignore the error
}
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
</script>
然后在后面的代码中:
protected void Page_Load(object sender, EventArgs e)
{
....
// If this is the initial loading of the page, restore the navigation tree view state
if (!IsPostBack)
reloadTreeviewState();
}
/*
* The Tools treeview state is stored in a cookie by the client before the user navigates
* away from the page. It's in the form of one character per node with 'e' being expanded.
*/
public void reloadTreeviewState()
{
try
{
HttpCookie cookie = Request.Cookies["ToolsTVExpand"];
if (cookie != null && cookie.Value != null)
{
int currIdx = 0;
foreach (TreeNode mainNode in TreeView1.Nodes)
{
currIdx = setNodeStates(mainNode, cookie.Value, currIdx);
}
}
}
catch (Exception e)
{
// Just keep going
}
}
protected int setNodeStates(TreeNode node, String stateInfo, int currIdx)
{
if (currIdx >= stateInfo.Length)
throw new Exception("State info shorter than list of nodes.");
Char state = stateInfo[currIdx];`enter code here`
if (state == 'e')
{
node.Expand();
}
currIdx++;
if (node.ChildNodes != null && node.ChildNodes.Count != 0)
{
foreach (TreeNode childNode in node.ChildNodes)
{
currIdx = setNodeStates(childNode, stateInfo, currIdx);
}
}
return currIdx;
}