views:

174

answers:

2

In my C# code-behind for an ASP.Net app, I have a variable being set and then I want to set a Javascript variable equal to it so I can do some work with it client-side. This C# variable is set in an event handler and it changes fairly changing fairly often.

So, my event handler is doing only this...

int scale = (int)myObject.Scale;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "JSVariables", "scale=" + scale, true);

Then I have in my JS I have the event handler simply alerting the value.

alert(scale);

Problem is the scale value is only set the very first time the event is fired. I can step through my C# code each time the event is raised and see that the RegisterClientScriptBlock is called and that scale is in fact getting different values.

How do I get this value to not be constant? Every time the RegisterClientScriptBlock line is being reached a new value should be being loaded into my JS scale variable but it's just staying as it initially was. Any ideas?

+2  A: 

RegisterClientScriptBlock registers your script by type (this.GetType()) and key ("JSVariables"). The next time RegisterClientScriptBlock is called in the same execution stack, it will check to see if a script for that type and key have already been registered, and if so, it will do nothing.

The purpose of this is to eliminate duplicate shared scripts. If five of your controls all rely on a shared JavaScript include, you only want to include it once on the page. So all controls can call the same include function and key, and ensure it is not included multiple times.

Rex M
+1  A: 

In Addition to what Rex said, if you are using ASP.NET Ajax, you'll need to use the RegisterClientScript methods on the ScriptManager if you want to update these values between partial postbacks, which it does sound like you are doing.

FlySwat