tags:

views:

275

answers:

2

I want to spit out a JS variable array like so from my custom control:

var myArray = [5410, 8362, 6638, 6758, 7795]

caveat is that I want it to also be unique to this control as this control will spit out more JavaScript that will utilize myArray. So I envision something like:

var [control'sID]myArray = [5410, 8362, 6638, 6758, 7795]

and then somehow the rest of the JavaScript that is spit out can reference this somehow where needed in the JS code. I've got certain methods in the other JavaScript that is being spit out that is using myArray.

+1  A: 

You can use ClientID
C# Example:

Response.Write("var " + this.ClientID + "myArray = [5410, 8362, 6638, 6758, 7795];");

VB Example:

Response.Write("var " & Me.ClientID & "myArray = [5410, 8362, 6638, 6758, 7795];")
Sani Huttunen
So you wouldn't use something like RegisterExpandoAttribute ? Just curious
CoffeeAddict
And what is ClientID vs. UniqueID?
CoffeeAddict
RegisterExpandoAttribute sets an attribute on an element after the page is loaded. It doesn't "spit" out javascript the way you want.
Sani Huttunen
UniqueID: my bad... it should be ClientID... otherwise you'll get errors.
Sani Huttunen
ClientID vs. UniqueID: UniqueID uses ":" while ClientID uses "_". You do not want ":" in your javascript.
Sani Huttunen
A: 

I think you want to generate a javascript array from your custom control, and you want to access it from your main library,

You can use your control's ClientID property to make your arrays unique.

And you can define a global array to keep the array's names to access them from your rest of the client scripts.

EDIT :

I just look at the RegisterExpandoAttribute method, it's an interesting method, I have never heard that before. In this example it looks like it you can add custom attributes to your control.

So you can use it in your custom control like that :

Just add a custom attribute that has your array items with comma separated. and when accessing the custom attribute, simply split them by comma. I think this will work for your question.

At your custom control :

Page.ClientScript.RegisterExpandoAttribute(this.ClientID
   , "myArray", "1,2,3,4");

At client side, get your array like that :

var myArray = 
   document.getElementById('<%= this.ClientID %>').getAttribute("myArray")).split(',');
Canavar
that's what I figured. I just wanted to see if you guys came up with another solution because I've been told I could use the RegisterExpandoAttribute but I don't see the value in it in my case.
CoffeeAddict