JavaScript not loaded when loading user control dynamically in an Ajax request

33 posts, 0 answers
  1. William
    William avatar
    5 posts
    Member since:
    Mar 2009

    Posted 06 Mar 2009 Link to this post

    To whom it may concern:

    Extremely weird, I try to add and remove user controls in an ASP Panel of the content page depending on an Ajax request from the navigation bar. There is no problem to load user controls dynamically in the code. However, when the user selects through the navigation bar, an Ajax request is sent to the content page wrapped in an Ajax panel for updating. At this point the last loaded user control is removed, and the user selected user control is added to the ASP Panel. All good, but JavaScript wrapped inside RadCodeBlock on the latest selected user control is not loaded. One thing worthwhile mentioning is that I load the second user control in the PreRender because AjaxRequest was triggered after the Load event and I need to flag the second control in the AjaxRequest handler for loading. I even try to use RegisterClientScriptBlock to register those JavaScripts in the code behind, but still doesn't work.

    William Feng
  2. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 09 Mar 2009 Link to this post

    Hello William,

    Try using the RegisterStartupScript method of the ScriptManager to register you client script.

    Give it a try and let me know if any issues arise.

    All the best,
    Iana
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. William
    William avatar
    5 posts
    Member since:
    Mar 2009

    Posted 12 Mar 2009 Link to this post

    Hi Iana

    It does not work as well. Here we go my master page:

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="TransGrid.Security.UI.MasterPages.Site" %>

     

    <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">

    <head>

        <title></title>

        <link href="../App_Themes/TransGrid/TG_WebApp.css" rel="stylesheet" type="text/css" />

        <link href="../App_Themes/TransGrid/PanelBar.css" rel="stylesheet" type="text/css" />

     

        <script type="text/javascript">

            function InitiateAsyncRequestComboBox(sender, eventArgs) {

                //debugger;

                var ajaxPanel = $find("<%= RadAjaxPanel1.ClientID %>");

                ajaxPanel.ajaxRequest("SelectedApplication:" + eventArgs.get_item().get_text());

            }

            

            function InitiateAsyncRequestPanelBar(sender, eventArgs) {

                //debugger;

                var ajaxPanel = $find("<%= RadAjaxPanel1.ClientID %>");

                ajaxPanel.ajaxRequest("ClickedItem:" + eventArgs.get_item().get_text());

            }

        </script>

     

        <asp:ContentPlaceHolder ID="head" runat="server">

        </asp:ContentPlaceHolder>

    </head>

    <body>

        <form id="form1" runat="server">

        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">

        </telerik:RadScriptManager>

        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">

            <AjaxSettings>

                <telerik:AjaxSetting AjaxControlID="RadAjaxManager1">

                    <UpdatedControls>

                        <telerik:AjaxUpdatedControl ControlID="RadAjaxPanel1"></telerik:AjaxUpdatedControl>

                    </UpdatedControls>

                </telerik:AjaxSetting>

            </AjaxSettings>

        </telerik:RadAjaxManager>

        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Height="75px"

            Width="75px" Transparency="20">

            <img alt="Loading..." src='<%= RadAjaxLoadingPanel.GetWebResourceUrl(Page, "Telerik.Web.UI.Skins.Default.Ajax.loading.gif") %>'

                style="border: 0;" />

        </telerik:RadAjaxLoadingPanel>

        <div id="wrap">

            <div id="header">

                <p id="toplinks">

                    Skip to: <a href="#content">Content</a> | <a href="#sidebar">Navigation</a> | <a

                        href="#footer">Footer</a></p>

                <h1>

                    <a href="../default.aspx">TransGrid<span class="fade" /> Central Security</a></h1>

                <div id="slogan">

                    user admin for hvpri, tcog, opslog and more &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp

                    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp &nbsp&nbsp&nbsp&nbsp

                    <telerik:RadComboBox ID="rcbApplication" runat="server" OnClientSelectedIndexChanged="InitiateAsyncRequestComboBox" AutoPostBack="false">

                    </telerik:RadComboBox>

                </div>

            </div>

            <div id="leftbar">

                <telerik:RadPanelBar ID="RadPanelBar1" runat="server" Width="210px" Skin="Outlook"

                    OnClientItemClicking="InitiateAsyncRequestPanelBar">

                    <Items>

                        <telerik:RadPanelItem Text="Application" ImageUrl="Img/mail.gif" Expanded="True"

                            ExpandedCssClass="ExpandedCssClass">

                            <Items>

                                <telerik:RadPanelItem ImageUrl="Img/mailPersonalFolders.gif" Text="Users" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/mailDeletedItems.gif" Text="Roles" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/mailInbox.gif" Text="Permissions" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/mailFolder.gif" Text="Data Groups" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/mailSent.gif" Text="AD Groups" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/mailOutbox.gif" Text="Configuration Settings"

                                    CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                            </Items>

                        </telerik:RadPanelItem>

                        <telerik:RadPanelItem Text="Administration" ImageUrl="Img/contacts.gif" Expanded="true"

                            ExpandedCssClass="ExpandedCssClass">

                            <Items>

                                <telerik:RadPanelItem ImageUrl="Img/contactsItems.gif" Text="Applications" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/contactsItems.gif" Text="AD Groups" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/contactsItems.gif" Text="Data Groups" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/contactsItems.gif" Text="Group Types" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/contactsItems.gif" Text="Permissions" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                            </Items>

                        </telerik:RadPanelItem>

                        <telerik:RadPanelItem Text="Support" ImageUrl="Img/tasks.gif" Expanded="true" ExpandedCssClass="ExpandedCssClass">

                            <Items>

                                <telerik:RadPanelItem ImageUrl="Img/tasksItems.gif" Text="Service Status" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/tasksItems.gif" Text="Service Interaction" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/tasksItems.gif" Text="Servers" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                                <telerik:RadPanelItem ImageUrl="Img/tasksItems.gif" Text="Links" CssClass="CustomCssClass1">

                                </telerik:RadPanelItem>

                            </Items>

                        </telerik:RadPanelItem>

                    </Items>

                </telerik:RadPanelBar>

            </div>

            <div id="content">

                <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1"

                    OnAjaxRequest="RadAjaxPanel1_AjaxRequest">

                    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

                    </asp:ContentPlaceHolder>

                </telerik:RadAjaxPanel>

            </div>

            <div id="footer">

                <p>

                    <a href="#header">Back to top</a><br />

                    &copy; 2008 <a href="#">TransGrid</a></p>

            </div>

        </div>

        </form>

    </body>

    </html>

    And the code behind the master page is as below:

    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 TransGrid.Security.Services;

     

    namespace TransGrid.Security.UI.MasterPages

    {

        public partial class Site : System.Web.UI.MasterPage

        {

            protected void Page_Load(object sender, EventArgs e)

            {

                // Load application combo box

                if (!Page.IsPostBack)

                {

                    AdministrationService service = new AdministrationService();

     

                    //TODO: reverse the order because app comm security has no users yet.

                    List<TransGrid.Security.Model.Application> applications = service.ApplicationsGetAll();                ;

                    applications.Reverse();

     

                    this.rcbApplication.DataSource = applications;

                    this.rcbApplication.DataValueField = "ApplicationId";

                    this.rcbApplication.DataTextField = "Name";

                    this.rcbApplication.DataBind();

     

                    Session["SelectedApplicationId"] = this.rcbApplication.SelectedValue;

                }

            }

     

            protected void RadAjaxPanel1_AjaxRequest(object sender, AjaxRequestEventArgs e)

            {

                if (e.Argument != null)

                {

                    string[] argumentArray = e.Argument.Split(":".ToCharArray(), 2);

     

                    // If the Ajax request originates from application combo box

                    if (argumentArray[0] == "SelectedApplication")

                    {

                        AdministrationService service = new AdministrationService();

     

                        List<Model.Application> appList = service.ApplicationsGetAll();

                        Session["SelectedApplicationId"] = appList.Single(z => z.Name == argumentArray[1]).ApplicationId;

                    }

                    // If the Ajax request originates from navigation panel bar

                    else if (argumentArray[0] == "ClickedItem")

                    {

                        Session["ClickedItem"] = argumentArray[1];

                    }

                }

            }

        }

    }

     

    In the content page, I load and unload users and roles controls depending on what user selects in the navigation bar:

     using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Web;

    using System.Web.SessionState;

    using System.Web.UI;

    using System.Web.UI.WebControls;

    using Telerik.Web.UI;

    using TransGrid.Security.Services;

     

    namespace TransGrid.Security.UI

    {

        public partial class _default : System.Web.UI.Page

        {

            private string LatestLoadedControlName

            {

                get

                {

                    return (string)ViewState["LatestLoadedControlName"];

                }

                set

                {

                    ViewState["LatestLoadedControlName"] = value;

                }

            }

     

            protected void Page_Load(object sender, EventArgs e)

            {

     

                object clickedItem = Session["ClickedItem"];

     

                if (clickedItem != null)

                {

                    switch (clickedItem.ToString())

                    {

                        case null:

                        case "Users":

                            LoadUserControl("~/User Controls/Users.ascx");

                            break;

     

                        case "Roles":

                            LoadUserControl("~/User Controls/Roles.ascx");

                            break;

     

                        default:

                            break;

                    }

                }

                else

                {

                    LoadUserControl("~/User Controls/Users.ascx");

                }

            }

     

            protected override void OnPreRender(EventArgs e)

            {

                object clickedItem = Session["ClickedItem"];

     

                if (clickedItem != null)

                {

                    switch (clickedItem.ToString())

                    {

                        case "Users":

                            LoadUserControl("~/User Controls/Users.ascx");

                            break;

     

                        case "Roles":

                            LoadUserControl("~/User Controls/Roles.ascx");

                            break;

     

                        default:

                            break;

                    }

                }

                else

                {

                    LoadUserControl("~/User Controls/Users.ascx");

                }

               

                base.OnPreRender(e);

            }

     

            private void LoadUserControl(string controlName)

            {

                if (LatestLoadedControlName != null)

                {

                    Control previousControl =

                        this.PanelContainer.FindControl(

                            LatestLoadedControlName.Split('.')[0].Replace("/", "").Replace("~", "").Replace(" ", ""));

                    if (previousControl != null)

                    {

                        this.PanelContainer.Controls.Remove(previousControl);

                    }

                }

     

                Control targetControl = this.PanelContainer.FindControl(controlName.Split('.')[0].Replace("/", "").Replace("~", "").Replace(" ", ""));

                if (targetControl == null)

                {

                    UserControl userControl = (UserControl)this.LoadControl(controlName);

     

                    userControl.ID = controlName.Split('.')[0].Replace("/", "").Replace("~", "").Replace(" ", "");

                    this.PanelContainer.Controls.Add(userControl);

                    LatestLoadedControlName = controlName;

                }

            }

        }

    }

     

    The structure of Users user control and Roles user control are very similar as below:

    Users.ascx

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Users.ascx.cs" Inherits="TransGrid.Security.UI.User_Controls.Users" %>

    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">

     

        <script type="text/javascript">

            function RowSelected(sender, args) {

                // Issue an Ajx Request

                var ajaxPanel = $find("<%= RadAjaxPanel1.ClientID %>");

                if (ajaxPanel !== null && args !== null) {

                    ajaxPanel.ajaxRequest("SelectedUserId:" + args.getDataKeyValue("UserId"));

                }

            }

     

            function GridCreated() {

                var RadGridUers = $find("<%= RadGridUsers.ClientID %>");

                var dataItems = RadGridUers.get_masterUsersTableView().get_dataItems();

                if (dataItems !== null && dataItems.length > 0) {

                    // Select the first row in the grid.

                    dataItems[0].set_selected("true");

                }

            }

        </script>

     

    </telerik:RadCodeBlock>

    <link href="../App_Themes/TransGrid/RadTabStrip.css" rel="stylesheet" type="text/css" />

    <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">

        <AjaxSettings>

            <telerik:AjaxSetting AjaxControlID="RadGridUsers">

                <UpdatedControls>

                    <telerik:AjaxUpdatedControl ControlID="RadGridUsers" LoadingPanelID="RadAjaxLoadingPanel1" />

                    <telerik:AjaxUpdatedControl ControlID="RadAjaxPanel1" LoadingPanelID="RadAjaxLoadingPanel1" />

                </UpdatedControls>

            </telerik:AjaxSetting>

        </AjaxSettings>

    </telerik:RadAjaxManagerProxy>

    <telerik:RadGrid ID="RadGridUsers" runat="server" AllowPaging="false" AllowSorting="true"

        AutoGenerateColumns="false" GridLines="None" CellPadding="0" ClientSettings-Scrolling-AllowScroll="true"

        ClientSettings-Scrolling-ScrollHeight="400px" ClientSettings-Scrolling-UseStaticHeaders="true"

        ClientSettings-Selecting-AllowRowSelect="true">

        <ClientSettings>

            <Selecting AllowRowSelect="true" />

            <ClientEvents OnRowSelected="RowSelected" />

            <ClientEvents OnGridCreated="GridCreated" />

        </ClientSettings>

        <MasterTableView DataKeyNames="UserId" ClientDataKeyNames="UserId" AutoGenerateColumns="false">

            <Columns>

                <telerik:GridBoundColumn UniqueName="UserId" HeaderText="User ID" DataField="UserId"

                    ReadOnly="true" Visible="false" />

                <telerik:GridBoundColumn UniqueName="ServiceNumber" HeaderText="Service Number" DataField="ServiceNumber"

                    ReadOnly="true" />

                <telerik:GridBoundColumn UniqueName="FirstName" HeaderText="First Name" DataField="FirstName"

                    ReadOnly="true" />

                <telerik:GridBoundColumn UniqueName="LastName" HeaderText="Last Name" DataField="LastName"

                    ReadOnly="true" />

                <telerik:GridBoundColumn UniqueName="Email" HeaderText="Email" DataField="Email"

                    ReadOnly="true" />

                <telerik:GridBoundColumn UniqueName="Phone" HeaderText="Phone" DataField="Phone"

                    ReadOnly="true" />

            </Columns>

        </MasterTableView>

    </telerik:RadGrid>

    <br />

    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" OnAjaxRequest="RadAjaxPanel1_AjaxRequest">

        <telerik:RadTabStrip ID="RadTabStrip1" runat="server" MultiPageID="MultiPageID1"

            SelectedIndex="0" Align="Justify" ReorderTabsOnSelect="true">

            <Tabs>

                <telerik:RadTab Text="User Permissions">

                </telerik:RadTab>

                <telerik:RadTab Text="Roles">

                </telerik:RadTab>

            </Tabs>

        </telerik:RadTabStrip>

        <telerik:RadMultiPage ID="MultiPageID1" runat="server" SelectedIndex="0">

            <telerik:RadPageView ID="RadPageView1" runat="server" CssClass="pageView" BorderStyle="None">

                <telerik:RadGrid ID="RadGridUserPermissions" runat="server" AllowPaging="false" AllowSorting="true"

                    AutoGenerateColumns="false" GridLines="None" CellPadding="0" ClientSettings-Scrolling-AllowScroll="true"

                    ClientSettings-Scrolling-ScrollHeight="200px" ClientSettings-Scrolling-UseStaticHeaders="true"

                    OnItemDataBound="RadGridRoles_ItemDataBound">

                    <MasterTableView DataKeyNames="PermissionId" AutoGenerateColumns="false">

                        <Columns>

                            <telerik:GridBoundColumn UniqueName="PermissionId" HeaderText="Permission ID" DataField="PermissionId"

                                ReadOnly="true" Visible="false" />

                            <telerik:GridBoundColumn UniqueName="Name" HeaderText="Name" DataField="Name" ReadOnly="true" />

                            <telerik:GridBoundColumn UniqueName="Description" HeaderText="Description" DataField="Description"

                                ReadOnly="true" />

                            <telerik:GridDropDownColumn UniqueName="GroupTypeId" ListTextField="Name" ListValueField="GroupTypeId"

                                HeaderText="Group Type" DataField="GroupTypeId" AllowSorting="true">

                            </telerik:GridDropDownColumn>

                        </Columns>

                    </MasterTableView>

                </telerik:RadGrid>

            </telerik:RadPageView>

            <telerik:RadPageView ID="RadPageView2" runat="server" CssClass="pageView" BorderStyle="None">

                <telerik:RadGrid ID="RadGridRoles" runat="server" AllowPaging="false" AllowSorting="true"

                    AutoGenerateColumns="false" GridLines="None" CellPadding="0" ClientSettings-Scrolling-AllowScroll="true"

                    ClientSettings-Scrolling-ScrollHeight="200px" ClientSettings-Scrolling-UseStaticHeaders="true"

                    OnItemDataBound="RadGridRoles_ItemDataBound">

                    <MasterTableView DataKeyNames="RoleId" ClientDataKeyNames="RoleId" AutoGenerateColumns="false">

                        <Columns>

                            <telerik:GridBoundColumn UniqueName="RoleId" HeaderText="Role ID" DataField="RoleId"

                                ReadOnly="true" Visible="false" />

                            <telerik:GridBoundColumn UniqueName="Name" HeaderText="Name" DataField="Name" ReadOnly="true" />

                            <telerik:GridBoundColumn UniqueName="Description" HeaderText="Description" DataField="Description"

                                ReadOnly="true" />

                            <telerik:GridDropDownColumn UniqueName="GroupTypeId" ListTextField="Name" ListValueField="GroupTypeId"

                                HeaderText="Group Type" DataField="GroupTypeId" AllowSorting="true">

                            </telerik:GridDropDownColumn>

                            <telerik:GridCheckBoxColumn UniqueName="IsActive" HeaderText="Is Active" DataField="IsActive"

                                AllowSorting="true">

                            </telerik:GridCheckBoxColumn>

                        </Columns>

                    </MasterTableView>

                </telerik:RadGrid>

            </telerik:RadPageView>

        </telerik:RadMultiPage>

    </telerik:RadAjaxPanel>

     Roles.ascx:

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Roles.ascx.cs" Inherits="TransGrid.Security.UI.User_Controls.Roles" %>

    <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">

        <ajaxsettings>

            <telerik:AjaxSetting AjaxControlID="RadGridRoles">

                <UpdatedControls>

                    <telerik:AjaxUpdatedControl ControlID="RadGridRoles" LoadingPanelID="RadAjaxLoadingPanel1" />

                </UpdatedControls>

            </telerik:AjaxSetting>

        </ajaxsettings>

    </telerik:RadAjaxManagerProxy>

    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server" >

     

        <script type="text/javascript">

            function GridCreatedRoles() {

                var RadGridRoles = $find("<%= RadGridRoles.ClientID %>");

                var dataItems = RadGridRoles.get_masterTableView().get_dataItems();

                if (dataItems !== null && dataItems.length > 0) {

                    // Select the first row in the grid.

                    dataItems[0].set_selected("true");

                }

            }

     

            function RowSelectedRoles(sender, args) {

                // Issue an Ajx Request

                var ajaxPanel = $find("<%= RadAjaxPanel1.ClientID %>");

                if (ajaxPanel !== null && args !== null) {

                    ajaxPanel.ajaxRequest("SelectedUserId:" + args.getDataKeyValue("UserId"));

                }

            }

        </script>

     

    </telerik:RadCodeBlock>

    <telerik:RadGrid ID="RadGridRoles" runat="server" AllowPaging="false" AllowSorting="true"

        AutoGenerateColumns="false" GridLines="None" CellPadding="0" OnItemDataBound="RadGridRoles_ItemDataBound"

        ClientSettings-Scrolling-AllowScroll="true" ClientSettings-Scrolling-ScrollHeight="400px"

        ClientSettings-Scrolling-UseStaticHeaders="true" ClientSettings-Selecting-AllowRowSelect="true">

        <clientsettings>

            <Selecting AllowRowSelect="true" />

            <ClientEvents OnGridCreated="GridCreatedRoles" />

            <ClientEvents OnRowSelected="RowSelectedRoles" />

        </clientsettings>

        <mastertableview datakeynames="RoleId" clientdatakeynames="RoleId" autogeneratecolumns="false">

            <Columns>

                <telerik:GridBoundColumn UniqueName="RoleId" HeaderText="Role ID" DataField="RoleId"

                    ReadOnly="true" Visible="false" />

                <telerik:GridBoundColumn UniqueName="Name" HeaderText="Name" DataField="Name" ReadOnly="true" />

                <telerik:GridBoundColumn UniqueName="Description" HeaderText="Description" DataField="Description"

                    ReadOnly="true" />

                <telerik:GridDropDownColumn UniqueName="GroupTypeId" ListTextField="Name" ListValueField="GroupTypeId"

                    HeaderText="Group Type" DataField="GroupTypeId" AllowSorting="true">

                </telerik:GridDropDownColumn>

                <telerik:GridCheckBoxColumn UniqueName="IsActive" HeaderText="Is Active" DataField="IsActive"

                    AllowSorting="true">

                </telerik:GridCheckBoxColumn>

            </Columns>

        </mastertableview>

    </telerik:RadGrid>

    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">

    </telerik:RadAjaxPanel>


    However,  GridCreatedRoles and RowSelectedRoles are not loaded when selecting Roles in the navigation bar.


    Cheers

    William Feng

     

     

  5. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 13 Mar 2009 Link to this post

    Hello William,

    I prepared a sample project for you following your scenario.
    Please check it out and let me know what differce in your case.

    Sincerely yours,
    Iana
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  6. William
    William avatar
    5 posts
    Member since:
    Mar 2009

    Posted 14 Mar 2009 Link to this post

    Hello Iana

    Thanks for your time and effort.

    I added a RadGrid on your WebUserControl2 as below:

    <%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl2.ascx.cs" Inherits="WebUserControl2" %>
    <%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
    WebUserControl2<br />

    <asp:Button ID="Button1" runat="server" Text="Update" OnClientClick="if(!updateClick()) return false;" OnClick="Button1_Click" /><br />
    <asp:Label ID="Label1" runat="server"></asp:Label>
    <telerik:RadGrid ID="RadGridRoles" runat="server" AllowPaging="false" AllowSorting="true"
        AutoGenerateColumns="false" GridLines="None" CellPadding="0"
        ClientSettings-Scrolling-AllowScroll="true" ClientSettings-Scrolling-ScrollHeight="400px"
        ClientSettings-Scrolling-UseStaticHeaders="true" ClientSettings-Selecting-AllowRowSelect="true">
        <clientsettings>
            <Selecting AllowRowSelect="true" />
            <ClientEvents OnGridCreated="GridCreatedRoles" />
            <ClientEvents OnRowSelected="RowSelectedRoles" />
        </clientsettings>
        <mastertableview datakeynames="RoleId" clientdatakeynames="RoleId" autogeneratecolumns="false">
            <Columns>
                <telerik:GridBoundColumn UniqueName="RoleId" HeaderText="Role ID" DataField="RoleId"
                    ReadOnly="true" Visible="false" />
                <telerik:GridBoundColumn UniqueName="Name" HeaderText="Name" DataField="Name" ReadOnly="true" />
                <telerik:GridBoundColumn UniqueName="Description" HeaderText="Description" DataField="Description"
                    ReadOnly="true" />
            </Columns>
        </mastertableview>
    </telerik:RadGrid>
    <telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server">
    </telerik:RadAjaxPanel>

    And tweak the codebehind as below:

    public partial class WebUserControl2 : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string script = "function updateClick() { return confirm('Are you sure you wnat to update?'); }";
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "script2", script, true);

            StringBuilder script1 = new StringBuilder();
            script1.Append("function GridCreatedRoles() {");
            script1.Append("var RadGridRoles = $find('<%= RadGridRoles.ClientID %>');");

            script1.Append("if (RadGridRoles !== null) { alert('RadGridRoles found!'); ");
            script1.Append("var dataItems = RadGridRoles.get_masterTableView().get_dataItems();");
            script1.Append("if (dataItems !== null && dataItems.length > 0) {");
            script1.Append("return dataItems[0].set_selected('true'); } return confirm('RadGridRoles is not null'); }else return confirm('RadGridRoles is null');}");

            script1.Append(" function RowSelectedRoles() {");
            script1.Append("var ajaxPanel = $find('<%= RadAjaxPanel1.ClientID %>');");
            script1.Append("if (ajaxPanel !== null && args !== null) { alert('ajax panel found');");
            script1.Append("ajaxPanel.ajaxRequest('SelectedRoleId:' + args.getDataKeyValue('RoleId'));}else alert('ajax panel not found')}");

            //string script = "function updateClick() { return confirm('Are you sure you want to select?'); }";
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "script1", script1.ToString(), true);
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "updated " + DateTime.Now.ToString();
        }

        protected override void OnPreRender(EventArgs e)
        {
            List<Role> roles = new List<Role>();

            Role role1 = new Role();
            role1.RoleId = 1;
            role1.Name = "William";
            role1.Description = "Ask the question";

            Role role2 = new Role();
            role2.RoleId = 1;
            role2.Name = "Iana";
            role2.Description = "Help William";

            roles.Add(role1);
            roles.Add(role2);

            RadGridRoles.DataSource = roles;
            this.RadGridRoles.DataBind();

            base.OnPreRender(e);
        }
    }

    Role class is a simple model class for data binding:

    public class Role
    {
        private int _roleId;
        private string _name;
        private string _description;

        public int RoleId { get { return _roleId; } set { _roleId = value; } }

        public string Name { get { return _name; } set { _name = value; } }

        public string Description { get { return _description; } set { _description = value; } }
    }

    When you load WebUserControl2, this time, JavaScripts GridCreatedRoles and RowSelectedRoles are loaded dynamically, however, RadGridRoles and RadAjaxPanel1 can not be found, so the first row can not be selected.

    By the way, it will be worse if I wrap the javascript in a telerik:radCodeBloack on the markup WebUserControl2.ascx (I mean they are not loaded at all), even your updateClick one. I should be much greateful if you can tell me why.

    Best

    William Feng

  7. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 17 Mar 2009 Link to this post

    Hello William,

    Thank you for elaborating on your case.

    Try modifying your code as below and see if it makes any difference:

    protected void Page_Load(object sender, EventArgs e)  
    {  
        string script = "function updateClick() { return confirm('Are you sure you wnat to update?'); }";  
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "script2", script, true);  
     
        StringBuilder script1 = new StringBuilder();  
        script1.Append("function GridCreatedRoles() {");  
        script1.Append("var RadGridRoles = $find('" + RadGridRoles.ClientID + "');");  
     
        script1.Append("if (RadGridRoles !== null) { alert('RadGridRoles found!'); ");  
        script1.Append("var dataItems = RadGridRoles.get_masterTableView().get_dataItems();");  
        script1.Append("if (dataItems !== null && dataItems.length > 0) {");  
        script1.Append("return dataItems[0].set_selected('true'); } return confirm('RadGridRoles is not null'); }else return confirm('RadGridRoles is null');}");  
     
        script1.Append(" function RowSelectedRoles() {");  
        script1.Append("var ajaxPanel = $find('" + RadAjaxPanel1.ClientID + "');");  
        script1.Append("if (ajaxPanel !== null && args !== null) { alert('ajax panel found');");  
        script1.Append("ajaxPanel.ajaxRequest('SelectedRoleId:' + args.getDataKeyValue('RoleId'));}else alert('ajax panel not found')}");  
     
        //string script = "function updateClick() { return confirm('Are you sure you want to select?'); }";  
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "script1", script1.ToString(), true);  

    When you register the client script through the ScriptManager, you do not need to wrap it in RadCodeBlock as you do need the server tags in the script.

    Give it a try and let me know how it goes.

    Sincerely yours,
    Iana
    the Telerik team


    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  8. William
    William avatar
    5 posts
    Member since:
    Mar 2009

    Posted 17 Mar 2009 Link to this post

    Hi Iana

    It is getting better, by changing <%= RadGridRoles.ClientID %> to RadGridRoles.ClientID, function GridCreatedRoles starts to work, however, the second function RowSelectedRoles still failed to find the RadAjaxPanel1, thus I can't trigger the AjaxRequest from the selected role.

    Secondly, I might have not stated my question clearly in my last thread. The real point is, when I wrap these two JavaScript functions inside a RadCodeBlock in the markup of the user control, why aren't they loaded at all? If I have to register them in the code behind, it is less intuitive and makes debugging very difficult.

    Cheers

    William
  9. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 19 Mar 2009 Link to this post

    Hello William,


    This is the proper way of accessing the AjaxPanel control. However I can suggest you to use the main page RadAjaxManager in this case. You can access it as below:

    RadAjaxManager.GetCurrent(Page) 
     And further information is available here (at the bottom).

    Regarding your second question:
    Unfortunately when user controls are loaded with RadAjax, their client script could not be registered by the RadAjaxManager/RadAjaxPanel control. Therefore they should be registered through the ScriptManager.

    Additionally, while testing with inline javascript, you can disable ajax temporary.

    I hope this helps.

    Greetings,
    Iana
    the Telerik team


    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  10. Zeke Sheppard
    Zeke Sheppard avatar
    32 posts
    Member since:
    Oct 2009

    Posted 16 Feb 2010 Link to this post

    I am encountering the a similar scenario when attempting to call a javascript function in a dynamically loaded user control. It cannot find the function specified. If the function is placed in the container page, the function is found, but it the controls on the .ascx cannot be found.

    How can I create and call a javascript function on a dynamically loaded user control? The explanation given above never seemed to actually address that issue.
  11. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 18 Feb 2010 Link to this post

    Hi Zeke,

    You can check the sample I attached previously in this thread to see how you can register the client scripts in the dynamically loaded control code behind.

    Additionally, you can refer to this forum thread discussing the same subject.

    Best wishes,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  12. Zeke Sheppard
    Zeke Sheppard avatar
    32 posts
    Member since:
    Oct 2009

    Posted 18 Feb 2010 Link to this post

    In reviewing the many threads on your site regarding this issue, it appears that none provide a workable solution, including the link you provided, to the issue of accessing javascript functions without the using RegisterStartupScript.

    Please state clearly if that assumption is correct, otherwise provide some insight on how to get this to work. BTW, inheritiing from RadAjaxPage is not an option, the assumption is that introducing any new Rad code would solve one simple problem, and introduce several more difficult ones.
  13. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 18 Feb 2010 Link to this post

    Hi Zeke,

    Currently I suggest that you use the ScriptManager.RegisterStartupScript method to register the scripts of a dynamically loaded control. Thus you can be sure the javascript would work as expected.

    Additionally, as this issue is forwarded to our developers I hope we find soon a resolution for it.

    I hope this helps.

    Greetings,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  14. Zeke Sheppard
    Zeke Sheppard avatar
    32 posts
    Member since:
    Oct 2009

    Posted 18 Feb 2010 Link to this post

    Just to confirm, you are indicating that it is necessary to load client side code from the server side? Incredible.

    One of the related threads has a global ajax handler in the container page to parse the message and allow this to work. Unfortunately, but not suprisingly, the sample does not work and that is clearly indicated in the user's responses. After the initial post, there has been no follow up by your group.

    Since this has been an issue for some time (at least two years, from looking at the messages), has anyone with your group ever given any thought to actually making this work?
  15. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 23 Feb 2010 Link to this post

    Hi Zeke,

    Please find the answer to your questions in this thread reviewing the last posts of my colleague Rosen.

    Best wishes,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  16. Zeke Sheppard
    Zeke Sheppard avatar
    32 posts
    Member since:
    Oct 2009

    Posted 23 Feb 2010 Link to this post

    The thread you referenced provides no new or useful information regarding this issue. Inheriting from RadAjaxPage is not (and never will be) an option. Security concerns preclude setting RestoreOriginalRenderDelegate  to True.

    What is the next step to getting this to work?
  17. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 23 Feb 2010 Link to this post

    Hi Zeke,

    Note that RadControls for ASP.NET AJAX are built on top of MS Ajax Framework. Unfortunately MS Ajax does not handle registration/elavuation of inline scripts in a dynamically loaded user control. Therefore RadAjax does not do it either.

    To overcome this issue, you can try the suggestions in this blog post or register the scripts manually as already explained.

    Kind regards,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  18. Zeke Sheppard
    Zeke Sheppard avatar
    32 posts
    Member since:
    Oct 2009

    Posted 23 Feb 2010 Link to this post

    Once again, your group continues to refer to threads that do not work (as clearly stated by the user comments, including my own in this case) or provide no useful information to resolving this issue.

    Please stop wasting my time with these circular references to non working 'suggestions'.

    Incredible, but not surprising.
  19. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 23 Feb 2010 Link to this post

    Hi Zeke,

    In order to provide a proper resolution for your case, I would ask you to send us a runnable project illustrating the issues you are facing. We will debug it then locally and provide you with a proper information/workaround.
    Other than this it is hard to determine what is the causing the problem and give you the right answer.

    All the best,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  20. Zeke Sheppard
    Zeke Sheppard avatar
    32 posts
    Member since:
    Oct 2009

    Posted 23 Feb 2010 Link to this post

    As copied from a similar thread on your site.....once again, no valid response provided.

    http://www.telerik.com/community/forums/aspnet-ajax/ajax/radajax-manager-does-not-load-js-files-in-dynamically-loaded-user-control.aspx

    'Your site has literally dozens of non working samples (pick any one), including this thread, yet no working solution from Telerik. Your group has never given any working solution to this issue. Please provide a solution to the original issue listed on this thread. This has not happened to date.

    As evidenced in this thread, even experienced Telerik users have given up on this technique, due to the inability to determine a workable solution. This appears to be an issue known to your group for at least two years.'

  21. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 24 Feb 2010 Link to this post

    Hi Zeke,

    As already explained, the problem is due to a limitation in the Ajax Framework. Please use any of the suggested workarounds to overcome it.

    Greetings,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  22. Zeke Sheppard
    Zeke Sheppard avatar
    32 posts
    Member since:
    Oct 2009

    Posted 24 Feb 2010 Link to this post

    Please review the response given in this thread...
    http://www.telerik.com/community/forums/aspnet-ajax/tooltip/clientevents-of-usercontrol-in-tooltip-undefined.aspx

    It appears to be a Telerik related issue that you are aware of. To quote;

    'Hi guys,

    This problem occurs when other RadControls are used in the loaded user control and we are aware of it. there is a workaround but the workaround itself as well as the solution is pretty complex and also uneffective for this particular case (it is handy in simple scenarios where the user control is not diplicated as many times on the pages). I strongly recommend to better implement the solution I have already suggested in my previous post which for your convenience I pasted below:

    Kind regards,
    Svetlina
    the Telerik team '
  23. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 25 Feb 2010 Link to this post

    Hello Zeke,

    It seems we are talking for different issues. Here it was discussed the problem with the inline scripts in a user control which is loaded dynamically via ajax and the fact that these scripts are not registered properly and how to workaround it.
    However if you want us to really help you solve the issues you are facing, instead of discussing separate issues in different threads, I would suggest you to open a formal support ticket and describe and illustrate them in details there. Thus we could do our best to find a proper resolution for you.

    Regards,
    Iana
    the Telerik team

    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
  24. jose luis
    jose luis avatar
    20 posts
    Member since:
    Apr 2011

    Posted 25 Aug 2011 Link to this post

    Hi is there in the support ticket an answer for this?

    my scenario is similar to described:

    a user control with java script code on it.

    this user control is loaded by a page from an aync ajax call on a raddock and the javascript in the user control is not found.

    Thanks

  25. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 26 Aug 2011 Link to this post

    Hello Jose,

    How are you registering the script? If it is declarative added in the user control markup, see if wrapping it with a RadScriptBlock help. If the issue persists, you will need to register it through the ScriptManager.RegisterStartupScript() method.

    All the best,
    Iana
    the Telerik team

    Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

  26. jose luis
    jose luis avatar
    20 posts
    Member since:
    Apr 2011

    Posted 27 Aug 2011 Link to this post

    hello
    i have registered using:

    ScriptManager.RegisterStartupScript(up, typeof(UpdatePanel), "setup2", "pueseso();", true);


    becasue the loaded control is inside and update panel.
    now the script is in the markup of the page but it not executed until you refresh the page?
    the pueseso() function should be started, correct? if not how can i start the javascript ?

    PD. the javascript belongs to the usercontrol and can not be written outside it.

    Thanks a looooooot
  27. Iana Tsolova
    Admin
    Iana Tsolova avatar
    3388 posts

    Posted 30 Aug 2011 Link to this post

    Hi Jose,

    What if you change the code as below:
    ScriptManager.RegisterStartupScript(Page, typeof(Page), "setup2", "pueseso();", true);

    Additionally, note that it is not suggested to use multiple ajax controls, like RadAjaxManager, RadAjaxPanel, ASP:UpdatePanel to ajaxify the same page content. I suggest that you choose only one of them.

    Kind regards,
    Iana
    the Telerik team

    Thank you for being the most amazing .NET community! Your unfailing support is what helps us charge forward! We'd appreciate your vote for Telerik in this year's DevProConnections Awards. We are competing in mind-blowing 20 categories and every vote counts! VOTE for Telerik NOW >>

  28. jose luis
    jose luis avatar
    20 posts
    Member since:
    Apr 2011

    Posted 01 Sep 2011 Link to this post

    hello

    in this post forum post i paste a code and the problem still persist.

    Thnak you very much
  29. vlad
    vlad avatar
    21 posts
    Member since:
    Aug 2007

    Posted 05 Jan 2012 Link to this post

    Hello

    For all people still breaking their heads (because they logically want javascript in ascx file, not in code behind), simply :

    <div id="uxDiv_ScriptBlock" runat="server" style="display:none;">
    <script type="text/javascript">
     
        function test() {
            alert("here");
        }
     
    </script>
    </div>

    And in code-behind

    protected void Page_Load(object sender, EventArgs e)
    {
        //register script
        String script = uxDiv_ScriptBlock.InnerText.Replace(Environment.NewLine, "");
        ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "Scripts", script, false);
    }

    That's it, you have javascript with intellisense and script is correctly registered in ascx ajax loaded control.
  30. piotre6
    piotre6 avatar
    18 posts
    Member since:
    Apr 2011

    Posted 03 Jun 2012 Link to this post

    I have problems with your solution if code coontains <%= %>  like below

    <div id="uxDiv_ScriptBlock" runat="server" style="display:none;">
    <script type="text/javascript">
       
        function test() {
            var text = $find('<%= tb1.ClientID %>');
            alert(text);
        }
       
    </script>
    </div>
    <asp:RadTextBox runat="server" ID="tb1"></telerik:RadTextBox>
  31. Robert
    Robert avatar
    253 posts
    Member since:
    Aug 2007

    Posted 14 Sep 2012 Link to this post

    Vlad,

    I tried your solution (and every possible permutation I could think of) but none seemed to work.

    In my case I want some initial Javascript to run immediately:

    var yPos0, yPos1, yPos2, yPos3;
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(BeginDivScrollRequestHandler);
    prm.add_endRequest(EndDivScrollRequestHandler);

    Is it possible that your solution only loads Javascript functions but can't immediately launch code?  If so, is there a way to do the latter?

    Robert
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017