Wednesday, March 28, 2012

calling external javascript functions/ library from within an update panel

I have an application with a large number of javaScript functions that reside in external .js files. User controls that reference these files work perfectly.

When usercontrols inside updatepanels call the external javascript functions and libraries, they fail with 'object not found' errors.

I tested using the scriptmanager.registerclientscriptblock by adding a concatenated string with a simple function and it worked. But this is a bad way to do things both from a debugging standpoint as well as ease of code. There must be a better way?

Dim scriptTextAsString

scriptText = _

"function prepareToClose() {"

& _

"alert('prepare to close');"

& _

"test();"

& _

" }"

System.Web.UI.ScriptManager.RegisterClientScriptBlock(

Me.btnLoad,Me.GetType(),"prepare_close", scriptTextTrue)

btnLoad.Attributes.Add(

"onCLick","prepareToClose(); return false;")

What is the best way to do this?

Unless someone has a better solution, here is what I did. Basically, I load the external file into a string and use the rgisterScriptBlock...everything works well and there is still just 1 instance of the scripts for easy maintenance and other non-ajax pages can use them. Here is the code for anyone interested.:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me.btnClose, Me.GetType(), "objectives", regLongScript("objectives.js"), True)


...

Private Function regLongScript(ByVal incoming_name As String) As String
Dim objStreamReader As IO.StreamReader
Try
Dim file_name As String = ""
file_name = Request.PhysicalApplicationPath & "a\js_scripts\" & incoming_name
objStreamReader = File.OpenText(file_name)
Return objStreamReader.ReadToEnd()

Catch ex As Exception
Return ""
Finally
objStreamReader.Close()
End Try
End Function


Here's how I've been doing it:

ScriptManager.RegisterStartupScript(

UpdatePanelTest,

UpdatePanelTest.GetType(),

"keyValue",

"alert('test')",

true);


Here's how I've been doing it:

ScriptManager.RegisterStartupScript(

UpdatePanelTest,

UpdatePanelTest.GetType(),

"keyValue",

"alert('test');",

true);

No comments:

Post a Comment