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

How to insert javascript after an AJAX Response

8 Answers 410 Views
Ajax
This is a migrated thread and some comments may be shown as answers.
Elian
Top achievements
Rank 1
Elian asked on 12 Mar 2009, 04:46 PM
Hi

I'm trying to load a UserControl with Page.Load(), the user control has a RadComboBox and I need the javascript code to handle the ComboBox events, but the javascript isn't loaded.
I tried with the SrciptManager.RegisterClientScriptBlock() and the RadAjaxManager.GetCurrent(this.Page).ResponseScripts.
the second let me put code like alert('hello') and it work, but if I put some like RadAjaxManager.GetCurrent(this.Page).ResponseScripts.Add("function hello(){alert('hello');}") and try to call it don't.
the user control ChartWidget.ascx
... 
    <telerik:RadAjaxPanel ID="AjaxPanel1" runat="server" Height="200px" Width="300px"
            <telerik:RadComboBox ID="ChartSelector" runat="server" Height="150px" Width="200"  OnClientDropDownOpened="OnClientDropDownOpenedHandler"
            <ItemTemplate> 
                <div id="div1"
                    <telerik:RadTreeView ID="Charts" runat="server" OnClientNodeClicking="nodeClicking"
                    </telerik:RadTreeView> 
                </div>            
            </ItemTemplate> 
            <Items> 
                <telerik:RadComboBoxItem Text="" /> 
            </Items> 
        </telerik:RadComboBox> 
    </telerik:RadAjaxPanel> 
... 

the code behind
       protected void Page_Load(object sender, EventArgs e) 
        { 
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "RadDropDownFunc", 
                "function comboLoad(sender, eventArgs){sender.set_text(sender.get_items().getItem(0).get_value());}"+ 
                "function StopPropagation(e){if (!e) {e = window.event;}e.cancelBubble = true;}"+ 
                string.Format("function OnClientDropDownOpenedHandler(sender, eventArgs){var tree = sender.get_items().getItem(0).findControl('{0}'); var selectedNode = tree.get_selectedNode(); if (selectedNode){selectedNode.scrollIntoView();}}",this.ChartSelector.ClientID), 
                true); 
            LoadData(); 
        } 
        public void LoadData() 
        { 
            ChartSelectorData = new List<ChartListItem> 
            { 
                new ChartListItem { Text = "Nodo 1"NodeID=1 , ParentID=0}, 
                new ChartListItem { Text = "Nodo 2"NodeID=2 , ParentID=0}, 
                new ChartListItem { Text = "Nodo 3"NodeID=3 , ParentID=0}, 
                new ChartListItem { Text = "Nodo 1-1"NodeID=4 , ParentID=1}, 
                new ChartListItem { Text = "Nodo 1-2"NodeID=5 , ParentID=1}, 
                new ChartListItem { Text = "Nodo 2-1"NodeID=6 , ParentID=2}, 
                new ChartListItem { Text = "Nodo 2-2"NodeID=7 , ParentID=2}, 
                new ChartListItem { Text = "Nodo 3-1"NodeID=8 , ParentID=3
            }; 
            ChartSelectorDataBind(); 
            ChartSelectorInitialize(); 
        } 
        private void ChartSelectorDataBind() 
        { 
 
            RadTreeView tree = GetChartSelectorTreeView(); 
            tree.DataTextField = "Text"
            tree.DataNavigateUrlField = ""
            tree.DataFieldID = "NodeID"
            tree.DataFieldParentID = "ParentID"
            tree.DataSource = ChartSelectorData
            tree.DataBind(); 
        } 
 
        private void ChartSelectorInitialize() 
        { 
            RadTreeView tree = GetChartSelectorTreeView(); 
            foreach (RadTreeNode Node in tree.GetAllNodes()) 
            { 
                if (Node.Nodes.Count == 0) 
                { 
                    Node.ImageUrl = "~/Includes/Skin/Default/chart.gif"
                } 
            } 
        } 
        private RadTreeView GetChartSelectorTreeView() 
        { 
            return (RadTreeView)ChartSelector.Items[0].FindControl("Charts"); 
        } 

the code behind where i want to load
        protected void Button1_Click(object sender, EventArgs e) 
        { 
            chartWidget = LoadControl("~/widgets/ChartWidget.ascx", new object[] { }) as ChartWidget; 
            chartWidget.LoadData(); 
            Panel1.Controls.Clear(); 
            Panel1.Controls.Add(chartWidget); 
        } 
        private UserControl LoadControl(string UserControlPath, params object[] constructorParameters) 
        { 
            List<Type> constParamTypes = new List<Type>(); 
            foreach (object constParam in constructorParameters) 
            { 
                if (constParam != null) 
                    constParamTypes.Add(constParam.GetType()); 
 
            } 
            UserControl ctl = Page.LoadControl(UserControlPath) as UserControl; 
 
            ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray()); 
            constructor.Invoke(ctl, constructorParameters); 
            return ctl; 
        } 

the page where the usercontrol loads
... 
    <asp:ScriptManager ID="ScriptManager1" runat="server"
    </asp:ScriptManager> 
    <telerik:RadAjaxManager ID="AjaxManager1" runat="server"
        <AjaxSettings> 
            <telerik:AjaxSetting AjaxControlID="Button1"
                <UpdatedControls> 
                    <telerik:AjaxUpdatedControl ControlID="Panel1" /> 
                </UpdatedControls>  
            </telerik:AjaxSetting> 
        </AjaxSettings> 
    </telerik:RadAjaxManager> 
... 
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> 
.. 
            <asp:Panel ID="Panel1" runat="server"
            </asp:Panel> 

8 Answers, 1 is accepted

Sort by
0
Iana Tsolova
Telerik team
answered on 13 Mar 2009, 04:02 PM
Hello Elian,

Try registering the scripts through the ScriptManager.RegisterStartupScript() method instead.

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.
0
Elian
Top achievements
Rank 1
answered on 13 Mar 2009, 05:05 PM
Hi

I tried that too with no luck. 
I make it work putting the javascript in Default.aspx hardcoding the ChartSelector.ClientID like this

        function nodeClicking(sender, args) 
        { 
            var comboBox = $find("ctl00_holderMainBody_ChartControl_ChartSelector"); 
5             var node = args.get_node() 
6             if (node._hasChildren()) {return;} 
7             comboBox.set_text(node.get_text()); 
8             comboBox.trackChanges(); 
9             comboBox.get_items().getItem(0).set_value(node.get_text()); 
            comboBox.commitChanges(); 
            comboBox.hideDropDown(); 
             
        } 

but if is possible I want to encapsulate it in the UserControl.

PS: in the example I forgot to reload the UserControl in Default.aspx Page_Load to make it work correctly

0
Iana Tsolova
Telerik team
answered on 16 Mar 2009, 12:19 PM
Hello Elian,

I went through your code again, and I see that you have RadAjaxPanel in the dynamically loaded user control. Please try removing it and see if it makes any difference.

Additionally, I tried testing your sample but due to missing resources, I could not run it.

Regards,
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.
0
Elian
Top achievements
Rank 1
answered on 17 Mar 2009, 03:20 PM
Yes , I tried removing the AjaxPanel but is still not working
in this example I put the javascript in ChartWidget.aspx, if this code is moved to Default.aspx it works perfect, in fact is what i'm using now, but I need to encapsulate in the widget.

Here it is all the code needed to try it

\Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PerfManPortal.Web._Default" %> 
 
<%@ 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 runat="server"
    <title></title
</head> 
 
 
<body> 
    <form id="form1" runat="server"
    <asp:ScriptManager ID="ScriptManager1" runat="server"
    </asp:ScriptManager> 
    <telerik:RadAjaxManager ID="AjaxManager1" runat="server"
        <AjaxSettings> 
            <telerik:AjaxSetting AjaxControlID="Button1"
                <UpdatedControls> 
                    <telerik:AjaxUpdatedControl ControlID="Panel1" /> 
                </UpdatedControls>  
            </telerik:AjaxSetting> 
        </AjaxSettings> 
    </telerik:RadAjaxManager> 
    <div> 
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> 
        <br /> 
        <asp:TextBox ID="txtResourceId" runat="server"></asp:TextBox><asp:Label ID="Label2" runat="server" Text="ResourceId"></asp:Label> 
        <br /> 
        <asp:TextBox ID="txtPFlag" runat="server"></asp:TextBox><asp:Label ID="Label4" runat="server" Text="PFlag"></asp:Label> 
        <br /> 
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> 
    </div> 
    <div> 
            <asp:Panel ID="Panel1" runat="server"
            </asp:Panel> 
    </div> 
    </form> 
</body> 
</html> 
 
 


\Default.aspx.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using PerfManPortal.Web.DomainServices; 
using System.Reflection; 
using PerfManPortal.Web.Widgets; 
 
 
namespace PerfManPortal.Web 
    public partial class _Default : System.Web.UI.Page 
    { 
        private UserControl control; 
 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            if (!IsPostBack) 
            { 
                txtResourceId.Text = "1501"
                txtPFlag.Text = "1"
            } 
 
            Panel1.Controls.Clear(); 
 
 
            string controlID = ViewState["LoadedControl"as string
            if(controlID != null
            { 
                switch(controlID) 
                { 
 
                    case "ChartWidget"
                        control = LoadControl("~/widgets/ChartWidget.ascx"new object[] { }); 
                        break
                    default
                        return
                } 
                control.ID = controlID; 
                Panel1.Controls.Add(control); 
            } 
 
        } 
 
        protected void Button1_Click(object sender, EventArgs e) 
        { 
 
            int ResourceID = Convert.ToInt32(txtResourceId.Text); 
            int PFlag = Convert.ToInt32(txtPFlag.Text); 
 
            control = LoadControl("~/widgets/ChartWidget.ascx"new object[] { }); 
            control.ID = "ChartWidget"
            ViewState["LoadedControl"] = control.ID; 
 
            Panel1.Controls.Clear(); 
            Panel1.Controls.Add(control); 
 
        } 
 
        private UserControl LoadControl(string UserControlPath, params object[] constructorParameters) 
        { 
            List<Type> constParamTypes = new List<Type>(); 
            foreach (object constParam in constructorParameters) 
            { 
                if (constParam != null
                    constParamTypes.Add(constParam.GetType()); 
            } 
 
            UserControl ctl = Page.LoadControl(UserControlPath) as UserControl; 
            ConstructorInfo constructor = ctl.GetType().BaseType.GetConstructor(constParamTypes.ToArray()); 
            constructor.Invoke(ctl, constructorParameters); 
 
            return ctl; 
        } 
    } 
 
 

\Widget\ChartWidget.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ChartWidget.ascx.cs" Inherits="PerfManPortal.Web.Widgets.ChartWidget" %> 
 
<%@ Register tagprefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" %> 
 
 
<telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server"
    <AjaxSettings> 
        <telerik:AjaxSetting AjaxControlID="btnShowChart"
            <UpdatedControls> 
                <telerik:AjaxUpdatedControl ControlID="divGraphic" /> 
            </UpdatedControls> 
        </telerik:AjaxSetting> 
        <telerik:AjaxSetting AjaxControlID="btnShowData" > 
            <UpdatedControls> 
                <telerik:AjaxUpdatedControl ControlID="divGraphic" /> 
            </UpdatedControls> 
        </telerik:AjaxSetting> 
    </AjaxSettings> 
</telerik:RadAjaxManagerProxy> 
<telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"
    <script type="text/javascript" language="javascript"
       function comboLoad(sender, eventArgs) 
            { 
                sender.set_text(sender.get_items().getItem(0).get_value()); 
            } 
        function nodeClicking(sender, args) 
        { 
            var comboBox = $find("ctl00_holderMainBody_ctl00_ChartSelector"); 
            var node = args.get_node() 
            if (node._hasChildren()) {return;} 
            comboBox.set_text(node.get_text()); 
            comboBox.trackChanges(); 
            comboBox.get_items().getItem(0).set_value(node.get_text()); 
            comboBox.commitChanges(); 
            comboBox.hideDropDown(); 
        } 
        function StopPropagation(e) 
        { 
            if (!e) {e = window.event;} 
            e.cancelBubble = true
        } 
        function OnClientDropDownOpenedHandler(sender, eventArgs) 
        { 
            var tree = sender.get_items().getItem(0).findControl("Charts"); 
            var selectedNode = tree.get_selectedNode(); 
            if (selectedNode){selectedNode.scrollIntoView();} 
        } 
    </script> 
</telerik:RadCodeBlock> 
<div style="float:left"
    <span style="font-size:16px;font-weight:bold">Chart:</span> 
     
        <telerik:RadComboBox ID="ChartSelector" runat="server" Height="150px" Width="200"  OnClientDropDownOpened="OnClientDropDownOpenedHandler" Skin="Gray"
            <ItemTemplate> 
                <div id="div1"
                    <telerik:RadTreeView ID="Charts" runat="server" OnClientNodeClicking="nodeClicking"
                    </telerik:RadTreeView> 
                </div>            
            </ItemTemplate> 
            <Items> 
                <telerik:RadComboBoxItem Text="Select Chart" Value="Select Chart" /> 
            </Items> 
        </telerik:RadComboBox> 
    <telerik:RadComboBox ID="ShowSelector" runat="server" Skin="Gray"
        <Items> 
            <telerik:RadComboBoxItem Text="Show Charts" Value="0" /> 
            <telerik:RadComboBoxItem Text="Show Data" Value="1" /> 
        </Items> 
 
<CollapseAnimation Type="OutQuint" Duration="200"></CollapseAnimation> 
    </telerik:RadComboBox> 
</div> 
<div style="float:right"
    <asp:Button ID="btnShow" runat="server" Text="Go" onclick="btnShow_Click" /> 
</div> 
<br clear="all" /> 
<div ID="divGraphic" runat="server"
 
</div> 
 
<%-- Properties --%> 
<asp:HiddenField ID="resourceID" runat="server" /> 
<asp:HiddenField ID="tabOptionMenuId" runat="server" /> 
<asp:HiddenField ID="pFlag" runat="server" /> 
 
 
         
         
         

\Widget\ChartWidget.ascx.cs
using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
using Telerik.Web.UI; 
using System.Collections.Generic; 
using PerfManPortal.Web.DomainServices; 
 
namespace PerfManPortal.Web.Widgets 
    public partial class ChartWidget : System.Web.UI.UserControl 
    { 
        #region Properties 
        /*
         * in the postback everithing but session is cleared, for the moment use session instead of whatever
         */ 
        public int ResourceID 
        {  
            get { return int.Parse(string.Format("{0}", Session["ResourceID"])); } 
            set { Session["ResourceID"] = value.ToString(); } 
        } 
        public int TabOptionMenuId 
        { 
            get { return int.Parse(string.Format("{0}", Session["TabOptionMenuId"])); } 
            set { Session["TabOptionMenuId"] = value.ToString(); } 
        } 
        public int PFlag 
        { 
            get { return int.Parse(string.Format("{0}", Session["PFlag"])); } 
            set { Session["PFlag"] = value.ToString(); } 
        } 
        private List<MyRadNode> ChartSelectorData 
        { 
            get { return Session["ChartSelectorData"as List<MyRadNode> ?? getChartSelectorData(); } 
            set { Session["ChartSelectorData"] = value; } 
        } 
        #endregion 
        #region Constructors 
 
        public ChartWidget() 
            : base() 
        { } 
 
        public ChartWidget(int resourceID, int currentTabOptionMenuId, int PFlag) 
            : base() 
        { 
            this.ResourceID = resourceID; 
            this.TabOptionMenuId = currentTabOptionMenuId; 
            this.PFlag = PFlag; 
        } 
        #endregion 
        #region Events 
 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            RadAjaxManagerProxy1.AjaxSettings.AddAjaxSetting(btnShow, divGraphic); 
            LoadData(); 
        } 
 
 
        protected void btnShow_Click(object sender, EventArgs e) 
        { 
            MyRadNode SelectedItem = (from MyRadNode Item in ChartSelectorData 
                                          where Item.Text.Equals(ChartSelector.SelectedValue) 
                                          select Item).ToArray()[0]; 
 
            if (ShowSelector.SelectedValue.Equals("0")) 
            { 
                divGraphic.InnerHtml = "<span>some Grpahic!</span>"
            } 
            else 
            { 
 
            } 
        } 
        #endregion 
        #region Databinding 
 
        public void LoadData() 
        { 
            ChartSelectorData = getChartSelectorData(); 
            ChartSelectorDataBind(); 
            ChartSelectorInitialize(); 
 
        } 
 
        private void ChartSelectorDataBind() 
        { 
 
            RadTreeView tree = GetChartSelectorTreeView(); 
            tree.DataTextField = "Text"
            tree.DataNavigateUrlField = ""
            tree.DataFieldID = "NodeID"
            tree.DataFieldParentID = "ParentID"
 
            tree.DataSource = ChartSelectorData; 
 
            tree.DataBind(); 
        } 
 
        private void ChartSelectorInitialize() 
        { 
 
            RadTreeView tree = GetChartSelectorTreeView(); 
 
            foreach (RadTreeNode Node in tree.GetAllNodes()) 
            { 
                if (Node.Nodes.Count == 0) 
                { 
                    Node.ImageUrl = "~/Includes/Skin/Default/chart.gif"
                } 
            } 
            setCustomIcon("Chart Test 3""~/Includes/Skin/Default/chart2.gif"); 
        } 
 
 
        private void setCustomIcon(String Text, String ImageUrl) 
        { 
            RadTreeView tree = GetChartSelectorTreeView(); 
            RadTreeNode Node = tree.FindNodeByText(Text); 
            if (Node != null
            { 
                Node.ImageUrl = ImageUrl; 
            } 
        } 
        #endregion 
        #region Methods 
 
        private RadTreeView GetChartSelectorTreeView() 
        { 
            return (RadTreeView)ChartSelector.Items[0].FindControl("Charts"); 
        } 
 
        private List<MyRadNode> getChartSelectorData() 
        { 
            try 
            { 
                ChartService service = new ChartService(); 
                return service.GetChartSelectorData(); 
            } 
            catch (Exception ex) 
            { 
                return new List<MyRadNode>(); 
            } 
        } 
        #endregion 
 
 
    } 
 
 

\DomainServices\ChartService.cs
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using Telerik.Web.UI; 
 
 
 
namespace PerfManPortal.Web.DomainServices 
    public class ChartService 
    { 
 
        public List<MyRadNode> GetChartSelectorData() 
        { 
            return new List<MyRadNode> 
            { 
                new MyRadNode{Text = "Folder 01", NodeID = 1, ParentID=0}, 
                new MyRadNode{Text = "Folder 02", NodeID = 2, ParentID=0}, 
                new MyRadNode{Text = "Folder 03", NodeID = 3, ParentID=0}, 
                new MyRadNode{Text = "Chart 04", NodeID = 4, ParentID=1}, 
                new MyRadNode{Text = "Chart 05", NodeID = 5, ParentID=1}, 
                new MyRadNode{Text = "Chart 06", NodeID = 6, ParentID=2}, 
                new MyRadNode{Text = "Chart 07", NodeID = 7, ParentID=3} 
            };  
        } 
    } 
 
    public class MyRadNode 
    { 
        public string Text { getset; } 
        public int NodeID { getset; } 
        public int ParentID { getset; } 
    } 
 
 

I will apreciate very much if you could help me to find a solution.
Thanks
0
Iana Tsolova
Telerik team
answered on 19 Mar 2009, 03:11 PM
Hi Elian,

Thank you for providing additional information on your case.

Unfortunately, when a user control is loaded dynamically with RadAjax, its client script could not be registered by the RadAjaxManager/RadAjaxPanel control. Therefore they should be registered through the ScriptManager.RegisterStartupScript() server method.

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.
0
Elian
Top achievements
Rank 1
answered on 19 Mar 2009, 07:30 PM
Ok, I understand that
but why it doesn't work with the ScriptManager.RegisterStartupScript() either?
I add this on the ChartWidget.ascx Page_Load()

            ScriptManager.RegisterStartupScript(this,this.GetType(),"Script"
            "function comboLoad(sender, eventArgs)"
                "{sender.set_text(sender.get_items().getItem(0).get_value());}"
            "function nodeClicking(sender, args){"
                "var comboBox = $find('ctl00_holderMainBody_ctl00_ChartSelector');"
                "var node = args.get_node();"
                "if (node._hasChildren()) {return;}"
                "comboBox.set_text(node.get_text());"
                "comboBox.trackChanges();"
                "comboBox.get_items().getItem(0).set_value(node.get_text());"
                "comboBox.commitChanges();"
                "comboBox.hideDropDown();}"
            "function StopPropagation(e){"
                "if (!e) {e = window.event;}"
                "e.cancelBubble = true;}"
            "function OnClientDropDownOpenedHandler(sender, eventArgs){"
                "var tree = sender.get_items().getItem(0).findControl('Charts');"
                "var selectedNode = tree.get_selectedNode();"
                "if (selectedNode){selectedNode.scrollIntoView();}}"
                true); 

and it should work, but no, also I read that if the functions to be register are Event Handlers they should go in ScriptManager.RegisterClientScriptManager(), I tried too and nothing.
maybe I'm doing something wrong when I register the script but I can't see the problem.
if you can make work this code, encapsulating the javascript in the widget, please let me know.
Thanks,
Elian
0
Accepted
Iana Tsolova
Telerik team
answered on 20 Mar 2009, 04:10 PM
Hello Elian,

I prepared a sample project for you based on the code from your previous post. It seems to work find on my side. Can you try it and let me know if I missed something out?

Looking forward your reply,
Iana
the Telerik team

Check out Telerik Trainer , the state of the art learning tool for Telerik products.
0
Elian
Top achievements
Rank 1
answered on 20 Mar 2009, 05:42 PM
Yeah!, it works perfect. Thank you very much.
I realized that the problem was using the widget when I call ScriptManager.RegisterStartupScript(). instead of that use the Page as the control that register the script. resolved the problem.

Again thank you very much.
Elian
Tags
Ajax
Asked by
Elian
Top achievements
Rank 1
Answers by
Iana Tsolova
Telerik team
Elian
Top achievements
Rank 1
Share this question
or