This is a migrated thread and some comments may be shown as answers.

ViewState Error in RadDock

1 Answer 140 Views
Dock
This is a migrated thread and some comments may be shown as answers.
David Moore
Top achievements
Rank 1
David Moore asked on 10 Feb 2009, 03:26 PM
I am trying to get a dashboard setup, I am loading different controls in and I keep getting the following javascript error when moving/removing the controls I've added.

"Sys.WebForms.PageRequestManagerServerErrorException: Failed to load viewstate.  The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request.  For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request."

It's clearly not able to access the controls correctly, and everything works if I turn the viewstate off, the problem is that I need the viewstate on for some of the docks I am adding to function properly. 

Here is my code for adding/loading docks.
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Web; 
using System.Web.SessionState; 
using System.Web.UI; 
using System.Web.Security; 
using System.Web.UI.WebControls; 
using System.Web.UI.HtmlControls; 
using System.Web.Script.Serialization; 
using Telerik.Web.UI; 
 
public partial class dashboard : System.Web.UI.Page 
 
    insidefbDataContext db = new insidefbDataContext(); 
    string cacheKey = "UserPreferences.PortalSession." + HttpContext.Current.User.Identity.Name.ToString(); 
 
    private List<DockState> CurrentDockStates 
        { 
            get 
            { 
                List<DockState> _currentDockStates = (List<DockState>)Cache[cacheKey]; 
                if (Object.Equals(_currentDockStates, null)) 
                { 
                    //Make an empty configuration list   
                    _currentDockStates = new List<DockState>(); 
 
                    //string strLoadedConfig = GetUserPreference("PortalConfiguration"); 
 
                    aspnetdbDataContext aspnetDB = new aspnetdbDataContext(); 
 
                    var dashboardItems = (from x in aspnetDB.aspnet_Users 
                                         select x).SingleOrDefault(c => c.UserName.Equals(User.Identity.Name.ToString())).dashboardItems; 
 
                     
                    //If we found nothing, leave the current state empty   
                    if (!string.IsNullOrEmpty(dashboardItems)) 
                    { 
                        string strLoadedConfig = dashboardItems.ToString();                                        
                        try 
                        { 
                            //Use the stored config   
                            //Convert the stored config to an array, splitting at the *s   
                            string[] aConfig = strLoadedConfig.Split('*'); 
                            DockState dsWorking = default(DockState); 
                            //Parse through the array, turning the dockstate strings into dockstates   
                            //Then add the dockstates to the dockstate list   
                            foreach (var strConfigItem in aConfig) 
                            { 
                                //Start a fresh dockstate   
                                dsWorking = new DockState(); 
                                //Parse the string back into dock settings   
                                dsWorking = DockState.Deserialize(strConfigItem); 
                                //Add the settings back into the current session   
                                _currentDockStates.Add(dsWorking); 
                            } 
                        } 
                        catch (Exception ex) 
                        { 
                        } 
 
                        Cache[cacheKey] = _currentDockStates; 
                    } 
                } 
                return _currentDockStates; 
            } 
            set 
            { 
                Cache[cacheKey] = value; 
 
                System.Text.StringBuilder sbListConverter = new System.Text.StringBuilder(); 
                foreach (DockState dockState in value) 
                { 
                    sbListConverter.AppendFormat("{0}*", dockState.ToString()); 
                } 
                string strDockConfig = sbListConverter.ToString().TrimEnd(Convert.ToChar("*")); 
 
                aspnetdbDataContext aspnetDB = new aspnetdbDataContext(); 
 
                aspnet_User activeUser = (from x in aspnetDB.aspnet_Users 
                                          select x).SingleOrDefault(c => c.UserName.Equals(User.Identity.Name.ToString())); 
 
                activeUser.dashboardItems = strDockConfig; 
                aspnetDB.SubmitChanges(); 
            } 
        } 
 
        protected void Page_Load(object sender, EventArgs e) 
        { 
 
            if (!IsPostBack) 
            { 
                LoadControlsCheckbox(); 
            } 
        } 
 
        protected void LoadControlsCheckbox() 
        { 
 
            IFBF.AspNet.Membership.IFBFMembership xEntity = new IFBF.AspNet.Membership.IFBFMembership(); 
            int entityid = xEntity.getEntityid(HttpContext.Current.User.Identity.Name); 
 
 
            t_countysecurity userCounty = (from z in db.t_countysecurities 
                                           where z.c_entityid.Equals(entityid) 
                                           select z).FirstOrDefault<t_countysecurity>(); 
            //if (userCounty != null) 
            if (true
            { 
                cbxWebParts.Items.Clear(); 
                ListItem itAlerts = new ListItem(); 
                itAlerts.Text = "Alerts"
                itAlerts.Value = "~/members/UserControls/Dashboard/Alerts.ascx"
                cbxWebParts.Items.Add(itAlerts); 
                ListItem itTask = new ListItem(); 
                itTask.Text = "Tasks"
                itTask.Value = "~/members/UserControls/Dashboard/Task.ascx"
                cbxWebParts.Items.Add(itTask); 
                ListItem itReports = new ListItem(); 
                itReports.Text = "Reports"
                itReports.Value = "~/members/UserControls/Dashboard/Reports.ascx"
                cbxWebParts.Items.Add(itReports); 
            } 
 
            ListItem itQuotes = new ListItem(); 
            itQuotes.Text = "Quotes"
            itQuotes.Value = "~/members/UserControls/Dashboard/Quotes.ascx"
            cbxWebParts.Items.Add(itQuotes); 
            ListItem itWeather = new ListItem(); 
            itWeather.Text = "Weather"
            itWeather.Value = "~/members/UserControls/Dashboard/Weather.ascx"
            cbxWebParts.Items.Add(itWeather); 
        } 
 
 
 
        public ArrayList GetZones() 
        { 
            ArrayList zones = new ArrayList(); 
            zones.Add(RadDockZone1); 
            zones.Add(RadDockZone2); 
 
            return zones; 
        } 
 
        protected void Page_Init(object sender, EventArgs e) 
        { 
            //Recreate the docks in order to ensure their proper operation 
            for (int i = 0; i < CurrentDockStates.Count; i++) 
            { 
                if (CurrentDockStates[i].Closed == false
                { 
                    RadDock dock = CreateRadDockFromState(CurrentDockStates[i]); 
                    //We will just add the RadDock control to the RadDockLayout. 
                    // You could use any other control for that purpose, just ensure 
                    // that it is inside the RadDockLayout control. 
                    // The RadDockLayout control will automatically move the RadDock 
                    // controls to their corresponding zone in the LoadDockLayout 
                    // event (see below). 
                    RadDockLayout1.Controls.Add(dock); 
                    //We want to save the dock state every time a dock is moved. 
                    CreateSaveStateTrigger(dock); 
                    //Load the selected widget 
                    LoadWidget(dock); 
                } 
            } 
        } 
 
        protected void RadDockLayout1_LoadDockLayout(object sender, DockLayoutEventArgs e) 
        { 
            //Populate the event args with the state information. The RadDockLayout control 
            // will automatically move the docks according that information. 
            foreach (DockState state in CurrentDockStates) 
            { 
                e.Positions[state.UniqueName] = state.DockZoneID; 
                e.Indices[state.UniqueName] = state.Index; 
            } 
        } 
 
        protected void RadDockLayout1_SaveDockLayout(object sender, DockLayoutEventArgs e) 
        { 
            //Save the dock state in the session. This will enable us 
            // to recreate the dock in the next Page_Init. 
            CurrentDockStates = RadDockLayout1.GetRegisteredDocksState(); 
        } 
 
        private RadDock CreateRadDockFromState(DockState state) 
        { 
            RadDock dock = new RadDock(); 
            dock.ID = string.Format("RadDock{0}", state.UniqueName); 
            dock.ApplyState(state); 
            dock.SkinID = "Office2007"
            dock.Command += new DockCommandEventHandler(dock_Command); 
            dock.Commands.Add(new DockCloseCommand()); 
            dock.Commands.Add(new DockExpandCollapseCommand()); 
 
            return dock; 
        } 
 
        private RadDock CreateRadDock(string title) 
        { 
            int docksCount = CurrentDockStates.Count; 
 
            RadDock dock = new RadDock(); 
            dock.UniqueName = Guid.NewGuid().ToString(); 
            dock.ID = string.Format("RadDock{0}", dock.UniqueName); 
            dock.Title = title; 
            dock.Text = string.Format("Added at {0}", DateTime.Now); 
            dock.Width = Unit.Pixel(300); 
 
            dock.Commands.Add(new DockCloseCommand()); 
            dock.Commands.Add(new DockExpandCollapseCommand()); 
            dock.Command += new DockCommandEventHandler(dock_Command); 
 
            return dock; 
        } 
 
        void dock_Command(object sender, DockCommandEventArgs e) 
        { 
            if (e.Command.Name == "Close"
            { 
                ScriptManager.RegisterStartupScript( 
                UpdatePanel1, 
                this.GetType(), 
                "RemoveDock"
                string.Format(@"function _removeDock() {{
    Sys.Application.remove_load(_removeDock);
    $find('{0}').undock();
    $get('{1}').appendChild($get('{0}'));
    $find('{0}').doPostBack('DockPositionChanged');
}};
Sys.Application.add_load(_removeDock);", ((RadDock)sender).ClientID, UpdatePanel1.ClientID), 
                true); 
 
            } 
        } 
 
        private void CreateSaveStateTrigger(RadDock dock) 
        { 
            //Ensure that the RadDock control will initiate postback 
            // when its position changes on the client or any of the commands is clicked. 
            //Using the trigger we will "ajaxify" that postback. 
            dock.AutoPostBack = true
            dock.CommandsAutoPostBack = true
 
            AsyncPostBackTrigger saveStateTrigger = new AsyncPostBackTrigger(); 
            saveStateTrigger.ControlID = dock.ID; 
            saveStateTrigger.EventName = "DockPositionChanged"
            UpdatePanel1.Triggers.Add(saveStateTrigger); 
 
            saveStateTrigger = new AsyncPostBackTrigger(); 
            saveStateTrigger.ControlID = dock.ID; 
            saveStateTrigger.EventName = "Command"
            UpdatePanel1.Triggers.Add(saveStateTrigger); 
        } 
 
        private void LoadWidget(RadDock dock) 
        { 
            if (string.IsNullOrEmpty(dock.Tag)) 
            { 
                return
            } 
            Control widget = LoadControl(dock.Tag); 
            dock.ContentContainer.Controls.Add(widget); 
        } 
 
 
        protected void ButtonAddDock_Click(object sender, EventArgs e) 
        { 
            foreach (ListItem li in cbxWebParts.Items) 
            { 
                if (li.Selected) 
                { 
                    RadDock dock = CreateRadDock(li.Text); 
                    UpdatePanel1.ContentTemplateContainer.Controls.Add(dock); 
 
                    ScriptManager.RegisterStartupScript( 
                    dock, 
                    this.GetType(), 
                    "AddDock" + dock.ClientID, 
                    string.Format(@"function _addDock() {{
    Sys.Application.remove_load(_addDock);
    $find('{1}').dock($find('{0}'));
    $find('{0}').doPostBack('DockPositionChanged');
}};
Sys.Application.add_load(_addDock);", dock.ClientID, chooseZone()), 
                    true); 
 
                    string blarg = chooseZone(); 
 
                    CreateSaveStateTrigger(dock); 
                    //Load the selected widget in the RadDock control 
                    dock.Tag = li.Value; 
                    //dock.Title = DroptDownWidget.SelectedItem.Text; 
                    LoadWidget(dock); 
                } 
            } 
 
            selectModule_MPE.Hide(); 
        } 
 
        protected string chooseZone() 
        { 
            int zoneOne = RadDockZone1.Docks.Count(); 
            int zoneTwo = RadDockZone2.Docks.Count(); 
 
            if (zoneOne > zoneTwo) 
            { return "ctl00_ctl00_masterContent_mainContent_RadDockZone2"; } 
            else 
            { return "ctl00_ctl00_masterContent_mainContent_RadDockZone1"; } 
        } 
 

and the aspx code:

<%@ Page Language="C#" MasterPageFile="~/resources/masterPages/insideFB_Members.master" Theme="insideFB" AutoEventWireup="true" CodeFile="dashboard.aspx.cs" Inherits="dashboard" Title="Dashboard" %> 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit"%> 
<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %> 
 
<asp:Content ID="Content1" ContentPlaceHolderID="mainContent" Runat="Server"
 
<div ID="pnlOpen" runat="server" class="modalPopup" style="display:none;"
 
<div style="width:500px;" id="searchDIV"
<div class="modalHeader" style="text-align:right;"
<asp:LinkButton ID="closeSearch" runat="server" Text="Close Window" ForeColor="White"></asp:LinkButton> 
    &nbsp;&nbsp;&nbsp;&nbsp; 
</div> 
</div> 
<div style="width:500px;" id="OpenDIV"
   
   <asp:CheckBoxList ID="cbxWebParts" runat="server"
    </asp:CheckBoxList> 
         
<br /> 
<asp:button runat="server" CssClass="button" id="ButtonAddDock" text="Add Dock" onclick="ButtonAddDock_Click" /> 
         
</div> 
</div> 
     
 <ajaxToolkit:ModalPopupExtender ID="selectModule_MPE" runat="server" 
    TargetControlID="imAdd" 
    PopupControlID="pnlOpen" 
    BackgroundCssClass="modalBackground"  
    CancelControlID="closeSearch" OkControlID="closeSearch" 
 />     
     
    <asp:ImageButton ID="imAdd" runat="server"  
        ImageUrl="~/resources/styles/graphics/addItem.gif" /> 
    <asp:ImageButton ID="imReset" runat="server" Visible="false"  
        ImageUrl="~/resources/styles/graphics/resetToDefault.gif" /> 
         
         
 
        <br/> 
<telerik:raddocklayout runat="server" id="RadDockLayout1" 
            onsavedocklayout="RadDockLayout1_SaveDockLayout" 
            onloaddocklayout="RadDockLayout1_LoadDockLayout"
            <telerik:raddockzone runat="server" id="RadDockZone1" SkinID="Office2007" width="445" MinHeight="200" style="float:left;margin-right:15px;background: #f5f4e8;"
            </telerik:raddockzone> 
            <telerik:raddockzone runat="server" id="RadDockZone2" SkinID="Office2007" width="445" MinHeight="200" style="background: #f5f4e8;float:left;"
            </telerik:raddockzone> 
            <div style="display:none"
                Hidden UpdatePanel, which is used to receive the new dock controls. 
                We will move them with script to the desired initial dock zone. 
                <asp:updatepanel runat="server" id="UpdatePanel1"
                    <triggers> 
                        <asp:asyncpostbacktrigger controlid="ButtonAddDock" eventname="Click" /> 
                    </triggers> 
                </asp:updatepanel> 
            </div> 
        </telerik:raddocklayout> 
</asp:Content> 
 
 

Any help would be appreciated, I've been banging my head on my desk/searching the net for a solution for a couple of days and nothing seems to work.

Thanks
~Dave

1 Answer, 1 is accepted

Sort by
0
Obi-Wan Kenobi
Top achievements
Rank 1
answered on 11 Feb 2009, 09:27 AM
Tags
Dock
Asked by
David Moore
Top achievements
Rank 1
Answers by
Obi-Wan Kenobi
Top achievements
Rank 1
Share this question
or