Question : Assign the value to a script global variable from the Server side code

HI,
   I need to set the value of a global script variable at the server code.
Say for e.g.
1) in test1.js, I have a variable called,
   var setFrmServerCode;
2) How to set its value to "test" from the code behind file, meaning from aspx.cs file
And its setting at the server code shud not  break the existing script file methods

Answer : Assign the value to a script global variable from the Server side code

One way would be to set the global object. This can cause a timing issue if your global JS variable is not available before this code runs. This is good for an example though.

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "script", _
        String.Format("setFrmServerCode={0}","SomeValueAsString")

So a second solution might be to create and set the global variable all at once from code behind. It will then be available for all your JS calls from then on.

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "script", _
        String.Format("var setFrmServerCode={0}","SomeValueAsString")

Another would be to create a function that sets the object and use an event like <body onload> to call the event. This way lets you control the timing and make sure your global variable is available before you try to set it.

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "script", _
        String.Format("function setGlobal(){{ setFrmServerCode= {0};}}","VariableDataAsString")

I've used all of these methods many times in the past with good success. I didn't convert them to C# as I already had these samples laying around. Hopefully you can see what to do and convert them yourself. If necessary I will convert them for you.
Random Solutions  
 
programming4us programming4us