OnInit event firing many times

4 posts, 0 answers
  1. Yen
    Yen avatar
    7 posts
    Member since:
    Mar 2011

    Posted 25 Oct 2011 Link to this post

    I have a page that has a RadDockLayout and the RadDocks are loaded dynamically in the OnInit event.  The issue I'm having is that the OnInit event gets fired the same number of times as the number of RadDocks that are generated.  So if I have 7 RadDocks, the OnInit gets fired 7 times.  I only want that event to fire once.  Please take a look at my code and let me know what I'm doing wrong.  Thanks.

     Test.aspx

    <telerik:RadAjaxPanel ID="ClientViewAjaxPanel" runat="server">
        <telerik:RadScriptManager ID="ScriptManager1" runat="server"
        </telerik:RadScriptManager>
          
        <div class="clientviewmaindiv"
            <center>     
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" ChildrenAsTriggers="false" UpdateMode="Conditional">
            <ContentTemplate>   
                <telerik:RadDockLayout runat="server" ID="RadDockLayout1" EnableEmbeddedSkins="true" Skin="Office2007" Visible="true">
                <div id="clientviewlayout" style="width:99%">
                <table cellpadding="0" cellspacing="0" class="tblClientViewLayout" style="width:99%"
                    <tr
                        <td class="tdClientViewleftcol"
                            <telerik:RadDockZone MinHeight="200px" BorderStyle="None" BorderWidth="0" runat="server" ID="RadDockZoneV1" Orientation="Vertical"></telerik:RadDockZone>
                        </td>                     
                        <td class="tdClientViewrightcol"
                            <telerik:RadDockZone MinHeight="200px" BorderStyle="None" BorderWidth="0" runat="server" ID="RadDockZoneV3" Orientation="Vertical"></telerik:RadDockZone
                        </td
                    </tr
                </table
                </div>
                </telerik:RadDockLayout>    
             </ContentTemplate>       
            </asp:UpdatePanel>     
            </center>             
        </div>     
        <telerik:RadWindowManager ID="RadWindowManager1" runat="server" ShowContentDuringLoad="false" VisibleStatusbar="false" ReloadOnShow="true" Modal="true" Skin="GIRadWindow" EnableEmbeddedBaseStylesheet="false" EnableEmbeddedSkins="false">
            <Windows>
                <telerik:RadWindow runat="server" ID="NewsWindow" Width="600" Height="450" BackColor="White" Behaviors="Close,Move,Resize"></telerik:RadWindow>
            </Windows>
        </telerik:RadWindowManager>
     </telerik:RadAjaxPanel>

    Test.apx.cs (some parameters have been removed for security purpose)
               protected override void OnInit(EventArgs e)
            {  
                base.OnInit(e);
                UserContext = (Context)Session[""];
      
                _ctx = new GBMDataContext();
      
                int userChartsCount = 0;
      
                DataSet userCharts = new DataSet("userCharts");
      
                using (SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[""].ConnectionString))
                              
                      SqlCommand command = new SqlCommand("", connection);
                    command.CommandTimeout = 3000;
                    command.CommandType = CommandType.StoredProcedure;
      
                    command.Parameters.Add(new SqlParameter("", ));
                    command.Parameters.Add(new SqlParameter("", ));
                    command.Parameters.Add(new SqlParameter("", ));
      
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = command;              
      
                    try
                    {
                        command.Connection.Open();
                        da.FillSchema(userCharts, SchemaType.Source);
                        da.Fill(userCharts);
                    }
                    catch
                    {
                        userChartsCount = 0;
                    }
                    finally
                    {
                        command.Connection.Close();
                    }
                }
      
                userChartsCount = userCharts.Tables[0].Rows.Count;
      
                if (userChartsCount > 0)
                {
                    RadDock dockWidget;
                    Control ctrlWidget;                
                    double rowCount = 1;
                    int widgetCount = 0;
       
                    if (userChartsCount > 1)
                    {
                        rowCount = Math.Ceiling(Convert.ToDouble(userChartsCount) / 2);
                    }
      
                    for (int x = 0; x < rowCount; x++)
                    {
                        for (int y = 0; y <= 1; y++)
                        {
                            if (widgetCount < userChartsCount)
                            {
                                dockWidget = new RadDock();                            
                                dockWidget.ID = (string)(userCharts.Tables[0].Rows[widgetCount]["DockId"]) + widgetCount.ToString();
                                dockWidget.Tag = (string)(userCharts.Tables[0].Rows[widgetCount]["DockId"]) + widgetCount.ToString();
                                dockWidget.DockMode = DockMode.Docked;
                                dockWidget.Skin = "Office2007";
                                dockWidget.Width = Unit.Pixel((int)userCharts.Tables[0].Rows[widgetCount]["DockWidth"]);
                                dockWidget.DockHandle = DockHandle.TitleBar;
                                dockWidget.DefaultCommands = Telerik.Web.UI.Dock.DefaultCommands.All;
      
                                dockWidget.Title = _ctx.fn_GetTextLabelTranslationByLabelName((string)userCharts.Tables[0].Rows[widgetCount]["Name"], UserContext.Language_RecordID);
                                ctrlWidget = LoadControl((string)userCharts.Tables[0].Rows[widgetCount]["ControlURL"]);                            
      
                                ctrlWidget.ID = (string)userCharts.Tables[0].Rows[widgetCount]["ControlId"];
                                RadDockLayout1.Controls.Add(dockWidget);
      
                                if (userCharts.Tables[0].Rows[widgetCount]["Zone"] == null)
                                {
                                    if (y == 0)
                                    {
                                        RadDockZoneV1.Controls.Add(dockWidget);
                                    }
                                    else
                                    {
                                        RadDockZoneV3.Controls.Add(dockWidget);
                                    }
                                }
                                else
                                {
                                    if ((int)userCharts.Tables[0].Rows[widgetCount]["Zone"] == 1)
                                    {
                                        RadDockZoneV1.Controls.Add(dockWidget);
                                    }
                                    else if ((int)userCharts.Tables[0].Rows[widgetCount]["Zone"] == 2)
                                    {
                                        RadDockZoneV3.Controls.Add(dockWidget);
                                    }
                                }
      
                                dockWidget.ContentContainer.Controls.Add(ctrlWidget);
                            }
      
                            widgetCount++;
                        }
                    }
                }
            }

    TestControl.ascx
    <telerik:RadAjaxPanel ID="ClientViewControlRadAjaxPanel" runat="server">
      
                <asp:Timer ID="ClientViewControlTimer" Interval="1" runat="server"></asp:Timer>
                <asp:MultiView ID="ClientViewControlMultiView" runat="server" ActiveViewIndex="0">
                <asp:View ID="ClientViewControlLoadingView" runat="server" >
                    <div id="loadingdiv" style="height:75px; margin-top:0px; margin-bottom:0px; padding:0px; background-repeat:no-repeat; background-position:center; background-image:url('../Skins/GIRadWindow/GIRadWindow/Window/loading.gif');"></div>
                </asp:View>
      
                <asp:View ID="ClientViewControlView" runat="server">
    <asp:LinqDataSource ID="dsNews" runat="server" OnSelecting="dsNews_Selecting" />
           <asp:ListView ID="lvNews" runat="server" DataKeyNames="RecordID"   DataSourceID="dsNews">   
                <LayoutTemplate>   
                <div id="itemPlaceholderContainer" runat="server">
                    <div id="itemplaceholder" runat="server"></div
                    </div>
                    <div style="clear: left; text-align:center; vertical-align: middle; float:none; width:100%;">
                    <asp:DataPager ID="pageTopics" runat="server" PageSize="3" PagedControlID="lvNews">    
                        <Fields>   
                            <asp:NextPreviousPagerField ButtonCssClass="pagerbuttons" ShowFirstPageButton="true" ButtonType="Image" ShowPreviousPageButton="false" ShowNextPageButton="false" FirstPageImageUrl="../Images/PagingFirst.gif" />   
                            <asp:NextPreviousPagerField ButtonCssClass="pagerbuttons" ShowFirstPageButton="false" ButtonType="Image" ShowPreviousPageButton="true" ShowNextPageButton="false" PreviousPageImageUrl="../Images/PagingPrev.gif" />   
                            <asp:NumericPagerField CurrentPageLabelCssClass="pagerbuttons" NumericButtonCssClass="pagerbuttons" ButtonCount="9" />   
                            <asp:NextPreviousPagerField ButtonCssClass="pagerbuttons" ShowFirstPageButton="false" ButtonType="Image" ShowPreviousPageButton="false" ShowNextPageButton="true" ShowLastPageButton="false" NextPageImageUrl="../Images/PagingNext.gif" />   
                            <asp:NextPreviousPagerField ButtonCssClass="pagerbuttons" ShowFirstPageButton="false" ButtonType="Image" ShowPreviousPageButton="false" ShowNextPageButton="false" ShowLastPageButton="true" LastPageImageUrl="../Images/PagingLast.gif" />   
                        </Fields>   
                   </asp:DataPager>
                   </div>
                </LayoutTemplate>   
                <ItemTemplate>   
                    <div>
                        <ul id="newsul">
                            <li id="newstitle"><asp:HyperLink runat="server" ID="titleNav" NavigateUrl='<%# Eval("OpenNewsURL")%>'><%# Eval("Name")%></asp:HyperLink>
                            <li id="newspub">
                            <div style="width:100%;margin:0;padding:0;">
                                <div style="text-align:left;float:left;">Published: <%# Eval("PublishDate")%></div>
                                <div style="text-align:right;"><asp:HyperLink runat="server" ID="newNav" ImageUrl="../Images/clientview/Globe.gif" NavigateUrl='<%# Eval("URL")%>' Target="_blank" /></div>
                             </div>                         
                            </li>
                            <li id="newsdesc"><%# Eval("Description").ToString()%></li>
                        </ul>
                    </div>   
                </ItemTemplate>   
                <EmptyDataTemplate><div id="emptylist" class="emptylist">No news found</div></EmptyDataTemplate>   
            </asp:ListView>
      
                      </asp:View>
                </asp:MultiView>
              
    </telerik:RadAjaxPanel>

    TestControl.ascx.cs
    protected override void OnLoad(EventArgs e)
            {
                base.OnLoad(e);
      
                if (IsPostBack)
                {
                    ClientViewControlTimer.Enabled = false;
                      
                    if (ClientViewControlMultiView.ActiveViewIndex == 0)
                    {
                        ClientViewControlMultiView.SetActiveView(ClientViewControlView);
                    }
                }
            }
      
            protected void dsNews_Selecting(object sender, LinqDataSourceSelectEventArgs args)
            {
      
                args.Result = LoadData();
            }
      
            private IList LoadData()
            {
      
                UserContext = (Context)Session[""];
                _userCulture = System.Globalization.CultureInfo.GetCultureInfo(UserContext.Locale);
                GBMDataContext ctx = new GBMDataContext();
      
                var NewsProfiles = from tmp2 in ctx.ApplicationProfileNewsRoomIntersects
                                   where tmp2.ApplicationProfile_RecordID == UserContext.ApplicationProfile_RecordID
                                   select tmp2.NewsRoom_RecordID;
      
                var q = from tmp in ctx.NewsRooms
                        where
                            (!(tmp.RecordExpiration.HasValue) || tmp.RecordExpiration.Value >= DateTime.UtcNow)
                            && tmp.LookupNewsCategory.Name != "Health and Benefits"
                            && NewsProfiles.Contains(tmp.RecordID) && (tmp.Tenant_RecordID == UserContext.TenantId || tmp.Tenant_RecordID == null)
                        orderby tmp.PublishDate descending
                        select new
                        {
                            tmp.RecordID,
                            Name = tmp.Name.Substring(0, 75),
                            PublishDate = tmp.PublishDate.ToString("d", _userCulture),
                            Description = tmp.Description != null ? tmp.Description.Substring(0, 175) : "",
                            URL = tmp.URL,
                            OpenNewsURL = "javascript:openNews('" + tmp.RecordID + "');"
                        };
      
                return q.ToList();
      
            }
  2. Slav
    Admin
    Slav avatar
    1355 posts

    Posted 28 Oct 2011 Link to this post

    Hi Yen,

    I tried to reproduce the described behavior, but to no avail. You can find attached my test page. Please compare it with your actual project and check if there are differences in the configuration. I have attached also a short clip, displaying the behavior that I encountered during the test.

    After examining your code I would like to bring several suggestions to your attention:
    1. It is better practice to place the RadScriptManager (or ScriptManager) control at the start of a page, right after the opening form tag, before the other ASP.NET controls.
    2. In certain scenarios nested UpdatePanels (which function similar to the RadAjaxPanel) could cause unexpected behavior, so I would suggest checking this article that explains such situations in greater detail.
    3 In the code behind of your page I noticed that you are adding the dynamically created RadDocks in the RadDockZones after inserting them in the RadDockLayout. I would recommend using the RadDock's Dock method instead, in order to place the dock control in a particular dock zone:
    RadDockLayout1.Controls.Add(dockWidget);
    dockWidget.Dock(RadDockZoneV1);

    Note that at the current circumstances I am mostly guessing as to what your setup is. If you are still unable to resolve your problems please try modifying the attached sample so that it matches your scenario or in case this isn't possible, prepare and send us a sample, runnable project that isolates your issue so that we can examine it locally and provide a more specific answer.

    Regards,
    Slav
    the Telerik team
    If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Yen
    Yen avatar
    7 posts
    Member since:
    Mar 2011

    Posted 28 Oct 2011 Link to this post

    Thanks, Slav.  Here is sample code that has the issue.  I'm loading user controls in the docks.  I couldn't upload the files so had to paste them here.

    TestDefault.aspx
    <%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeFile="TestDefault.aspx.cs" Inherits="_Default"  ViewStateMode="Disabled"%>
    <%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
    <body style="overflow:auto">
    <form id="Form1" runat="server">     
    <telerik:RadScriptManager ID="ScriptManager1" runat="server"
    </telerik:RadScriptManager>   
    <telerik:RadAjaxPanel ID="ClientViewAjaxPanel" runat="server">
        <div class="clientviewmaindiv"
            <center>     
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" ChildrenAsTriggers="false" UpdateMode="Conditional">
            <ContentTemplate>   
                <telerik:RadDockLayout runat="server" ID="RadDockLayout1" EnableEmbeddedSkins="true" Skin="Office2007" Visible="true">
                <div id="clientviewlayout" style="width:99%">
                <table cellpadding="0" cellspacing="0" class="tblClientViewLayout" style="width:99%"
                    <tr
                        <td class="tdClientViewleftcol"
                            <telerik:RadDockZone MinHeight="200px" BorderStyle="None" BorderWidth="0" runat="server" ID="RadDockZoneV1" Orientation="Vertical"></telerik:RadDockZone>
                        </td>                     
                        <td class="tdClientViewrightcol"
                            <telerik:RadDockZone MinHeight="200px" BorderStyle="None" BorderWidth="0" runat="server" ID="RadDockZoneV3" Orientation="Vertical"></telerik:RadDockZone
                        </td
                    </tr
                </table
                </div>
                </telerik:RadDockLayout>    
             </ContentTemplate>       
            </asp:UpdatePanel>     
            </center>             
        </div>     
        <telerik:RadWindowManager ID="RadWindowManager1" runat="server" ShowContentDuringLoad="false" VisibleStatusbar="false" ReloadOnShow="true" Modal="true" Skin="GIRadWindow" EnableEmbeddedBaseStylesheet="false" EnableEmbeddedSkins="false">
            <Windows>
                <telerik:RadWindow runat="server" ID="NewsWindow" Width="600" Height="450" BackColor="White" Behaviors="Close,Move,Resize"></telerik:RadWindow>
            </Windows>
        </telerik:RadWindowManager>
        </telerik:RadAjaxPanel>
    </form>
    </body>
    </html>


    TestDefault.aspx.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Telerik.Web.UI;
    using System.Collections;
      
    public partial class _Default : System.Web.UI.Page
    {
        protected override void OnInit(EventArgs e)
        {        
            RadDock dockWidget;
            Control ctrlWidget;            
            List<String[]> userCharts = new List<String[]>();
      
            userCharts.Add(new String[] {"dockContacts", "Contacts", "ctlSystemContacts.ascx", "ctlSystemContacts" });
            userCharts.Add(new String[] { "dockEvents", "Events", "ctlSystemEvents.ascx", "ctlSystemEvents" });
      
            for (int x = 0; x < userCharts.Count; x++)
            {
                  
                dockWidget = new RadDock();
                dockWidget.ID = userCharts[x][0];
                dockWidget.Tag = userCharts[x][0];
                dockWidget.DockMode = DockMode.Docked;
                dockWidget.Skin = "Office2007";
                dockWidget.Width = 200;
                dockWidget.DockHandle = DockHandle.TitleBar;
                dockWidget.DefaultCommands = Telerik.Web.UI.Dock.DefaultCommands.All;
      
                dockWidget.Title = userCharts[x][1];
                ctrlWidget = LoadControl(userCharts[x][2]);                  
      
                ctrlWidget.ID = userCharts[x][3];
                RadDockLayout1.Controls.Add(dockWidget);
      
                if (x == 0)
                {               
                    dockWidget.Dock(RadDockZoneV1);                
                }
                else
                {
                    dockWidget.Dock(RadDockZoneV3);                
                }
      
                dockWidget.ContentContainer.Controls.Add(ctrlWidget);                
            }
        }
      
        protected void Page_Load(object sender, EventArgs e)
        {
      
        }
    }

    ctlSystemEvents.ascx
    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ctlSystemEvents.ascx.cs" Inherits="ClientView_ctlSystemEvents" %>
    <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
    <telerik:RadAjaxPanel ID="ClientViewControlRadAjaxPanel" runat="server">    
        <asp:Timer ID="ClientViewControlTimer" Interval="1" runat="server"></asp:Timer>
        <asp:MultiView ID="ClientViewControlMultiView" runat="server" ActiveViewIndex="0">            
            <asp:View ID="ClientViewControlLoadingView" runat="server" >
            <div id="loadingdiv" style="height:75px; margin-top:0px; margin-bottom:0px; padding:0px; background-repeat:no-repeat; background-position:center; background-image:url('../Skins/GIRadWindow/GIRadWindow/Window/loading.gif');"></div>
            </asp:View>
            <asp:View ID="ClientViewControlView" runat="server">
                <asp:Label ID="Label1" runat="server" Text="Events"></asp:Label>
            </asp:View>
        </asp:MultiView>       
    </telerik:RadAjaxPanel>
      
                

    ctlSystemEvents.ascx.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Aon.DataModel;
    using System.Globalization;
      
    public partial class ClientView_ctlSystemEvents : System.Web.UI.UserControl
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
      
            if (IsPostBack)
            {
                ClientViewControlTimer.Enabled = false;
                //ClientViewControlUpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
                if (ClientViewControlMultiView.ActiveViewIndex == 0)
                {
                    ClientViewControlMultiView.SetActiveView(ClientViewControlView);
                }
            }
        }
    }



    ctlSystemContacts.ascx

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="ctlSystemContacts.ascx.cs" Inherits="ctlSystemContacts" %>
    <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
    <telerik:RadAjaxPanel ID="ClientViewControlRadAjaxPanel" runat="server">    
        <asp:Timer ID="ClientViewControlTimer" Interval="1" runat="server"></asp:Timer>
      
        <asp:MultiView ID="ClientViewControlMultiView" runat="server" ActiveViewIndex="0">            
        <asp:View ID="ClientViewControlLoadingView" runat="server" >
            <div id="loadingdiv" style="height:75px; margin-top:0px; margin-bottom:0px; padding:0px; background-repeat:no-repeat; background-position:center; background-image:url('../Skins/GIRadWindow/GIRadWindow/Window/loading.gif');"></div>
        </asp:View>
        <asp:View ID="ClientViewControlView" runat="server">            
            <asp:Label runat="server" Text="Contacts"></asp:Label>
         </asp:View>
        </asp:MultiView>        
    </telerik:RadAjaxPanel

    ctlSystemContacts.ascx.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Telerik.Web.UI;
    using System.Data;
      
    public partial class ctlSystemContacts : System.Web.UI.UserControl
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
      
            if (IsPostBack)
            {
                ClientViewControlTimer.Enabled = false;
                  
                if (ClientViewControlMultiView.ActiveViewIndex == 0)
                {
                    ClientViewControlMultiView.SetActiveView(ClientViewControlView);
                }
            }
        }   
    }
  5. Slav
    Admin
    Slav avatar
    1355 posts

    Posted 02 Nov 2011 Link to this post

    Hello Yen,

    Thank you very much for the provided sample! After examining your code I was able to detect the cause for the described behavior. In every one of the loaded user controls you have placed a RadAjaxPanel with a Ticker control. When the user controls are added into the RadDocks, the ticker inside each of them initiates an Ajax request and as a result the main page goes through a full life cycle. This happens once for every user control that you are loading, because after the postback you are disabling the Tickers.

    Please note that the encountered behavior is expected and it is not related to the RadDock controls. I would suggest removing the Tickers from your user controls, since I am mostly guessing as to what their purpose in your project is. If you need them, please describe the scenario you want to achieve, so that we can suggest an alternative solution, in case such is possible.

    Kind regards,
    Slav
    the Telerik team
    If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Back to Top