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
32 Answers, 1 is accepted
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.

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               
                   
<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 />
© 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
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.

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
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.

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
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) |
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.

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.
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.

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.
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.

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?
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.

What is the next step to getting this to work?
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.

Please stop wasting my time with these circular references to non working 'suggestions'.
Incredible, but not surprising.
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.

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.'
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.

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 '
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.

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
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 >>

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
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 >>


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.

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
>

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

If you need to launch code on execution, you have to use a small trick (at least that's what I do). Personally, I use a radgrid created event to execute startup code (inside registered js block of course), like this:
<script type="text/javascript">
function uxRadGrid_Created(sender, arg) {
//STARTUP JS CODE
}
</script>
If you don't need a radgrid in your ascx, you could create a dummy one (invisible), I don't think that it will affect your page performance.
Best

Developer Notes
Some DIV elements have their 'overflow-y' properties set to 'auto'. This lets a vertical scrollbar appear when needed. If this, and nothing else, is setup then it works fine except for one thing: After a partial postback, the position of the scrollbar is lost. This can be rather disconcerting to the user as suddenly the contents of the DIV shift position without any apparent reason why. So to correct this, special Javascript has been built which stores the Y-position before the postback and then restores it afterwards.
To implement this code in a Web Content Form or User Control, do the following:
1. In the layout page add this hidden field:
<asp:HiddenField ID="divScrollInit" runat="server" />
2. In the "(!IsPostBack)" or "(!Initialized)" construct of Page_Load initialize the hidden field:
divScrollInit.Value = "moduleName:div1,div2,...,divN"
Here are some examples:
- divScrollInit.Value = "GeneralInfo:divScroll";
- divScrollInit.Value = "EquipSubType:divScroll1,divScroll2,divScroll3";
That's it. Once this is done then the Javascript code, located in your external .JS file, will handle everything else.
var
dsInfo;
// Global variable used in the management of DIV Scroll values
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequestHandler);
function
InitializeRequestHandler(sender, eventArgs) {
// Note: Because this code is located in an external file, we can no longer reference any ASP.NET
// controls explicitly. Thus, the DIV inside each ProgressTemplate was specifically given
// an 'id' property with the value of 'progress'. With it, we can then reference its parent,
// which is the UpdateProgress control.
// Initialization of the DIV Scroll Management global variable
// -----------------------------------------------------------
// Reaching here, we're in one of three possible states:
// 1. 'dsInfo' is null.
// 2. 'dsInfo' has already been populated by the current page (ie. we haven't changed pages).
// 3. 'dsInfo' has been previously populated by a different page (ie. we've switched to a new page).
// We will only repopulate 'dsInfo' for cases #1 & #3.
if
($(
'[id$=_divScrollInit]'
).length > 0) {
var
dsInitArray = $(
'[id$=_divScrollInit]'
).val().split(
":"
);
var
module = dsInitArray[0];
var
divScrolls = dsInitArray[1];
// CDF string of one or more element IDs
if
(dsInfo ==
null
) {
// Case #1
dsInfo = module +
":"
;
$.each(divScrolls.split(
","
),
function
() {
dsInfo +=
this
.trim() +
",0;"
;
});
dsInfo = dsInfo.slice(0, -1);
// Remove trailing semicolon
}
else
if
(module == dsInfo.split(
":"
)[0]) {
// Case #2
// We don't actually need to do anything
}
else
{
// Case #3
dsInfo =
null
;
}
}
}
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function
BeginRequestHandler(sender, eventArgs) {
// Manages the DIV Scroll values
if
(dsInfo !=
null
) {
var
dsInfoNew =
""
;
var
module = dsInfo.split(
":"
)[0];
var
dsData = dsInfo.split(
":"
)[1];
$.each(dsData.split(
";"
),
function
() {
var
id0 =
this
.split(
","
)[0].trim();
// Note: Used 'id0' rather than 'id' so code is less confusing
var
newVal = 0;
// Default assumption
var
selSet = $(
'[id$='
+ id0 +
']'
);
if
(selSet.length > 0) {
var
div = $get(selSet[0].id);
if
(div !=
null
) {
newVal = div.scrollTop
}
}
dsInfoNew += id0 +
","
+ newVal +
";"
;
});
dsInfoNew = dsInfoNew.slice(0, -1);
// Remove trailing semicolon
dsInfo = module +
":"
+ dsInfoNew;
}
// End of managing DIV Scroll values
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function
EndRequestHandler(sender, eventArgs) {
// Manages the DIV Scroll values
if
(dsInfo !=
null
) {
var
dsData = dsInfo.split(
":"
)[1];
$.each(dsData.split(
";"
),
function
() {
var
id0 =
this
.split(
","
)[0];
var
newVal =
this
.split(
","
)[1];
var
selSet = $(
'[id$='
+ id0 +
']'
);
if
(selSet.length > 0) {
var
div = $get(selSet[0].id);
if
(div !=
null
) {
div.scrollTop = newVal;
}
}
});
}
// End of managing DIV Scroll values
}
