Trouble when including JavaScript block with Telerik Ajax Panel
Today I was having quite a bit of problem when I wanted to include javascript from a control inside a Telerik Ajax Panel. The javascript in question was dynamically generated and should only be added sometimes depending on what action was made inside the ajax panel.
The first thing I tried is the standard way of registering javascript blocks, namely using Page.ClientScript.RegisterClientScriptBlock. That didn’t work, which when I thought about it was logical as the script is added high up in the html and not inside the ajax panel.
Secondly, I read a bit on Telerik’s support pages. It suggested that I used RadAjaxPanel.EnableOutsideScripts and RadAjaxPanel.ResponseScripts. I didn’t get this to work either directly, and got outofmemory exception in javascript. Due to time constraints I didn’t investigate this properly. I will try and write and update soon, if I remember.
The last thing I tried was to just include the javascript inside the html of the ajax panel. Like the following code suggested I did this by using a LiteralControl, containing the script, that is inserted in the ajax panel’s control collection.
RadAjaxPanel panel = new RadAjaxPanel(); if (someCondition) { string myScript = "function MyAlert() { alert('Hello world'); }"; LiteralControl scriptControl = new LiteralControl(); script.Text = string.Format( @"<script type=""text/javascript"">{0}</script>", myFunction); panel.Controls.Add(scriptControl); Button alertButton = new Button(); alertButton.OnClientClick("MyAlert(); return false;"); panel.Controls.Add(alertButton); }
For the sake of simplicity the javascript that is dynamically added in this example is rather static. This turned out to work. I should mention that this trick will work just as well with the standard Microsoft ASP.NET Ajax Update Panel.