Blake Blackwell
Blake Blackwell

Reputation: 7795

Accessing JavaScript Properties in Custom ASP.NET AJAX Server Control

I am creating a custom ASP.NET AJAX server control in which multiple instances of the control may be placed on the page. That control wraps JavaScript objects, which I need access to those objects for each individual control. For example, the JavaScript object may have a property called "x" and control1 might have x set to 5 and control2 might x set to 10. How do I get access to each individual control's JavaScript objects? Here is a bit of a code snippet that might help:

HTML

    <CustomControl:MyControl ID="MyControl1" runat="server" x="5"/>
    <CustomControl:MyControl ID="MyControl2" runat="server" x="10"/>

JavaScript

alert(MyControl1.x); //result 5
alert(MyControl2.x); //result 10

Upvotes: 1

Views: 1674

Answers (3)

Blake Blackwell
Blake Blackwell

Reputation: 7795

Chris's suggested articles led me to the right solution. In order to get access to the JavaScript properties of a custom control, you must use the ScriptControl's library to execute the $find function to locate your control. For example:

JavaScript in ASP.NET page implementing control

var ctrl1 = $find("<%=MyControl1.ClientID%>");
var ctrl2 = $find("<%=MyControl2.ClientID%>");

ctrl.set_x(5);
alert(ctrl1.x); //result 5

ctrl2.set_x(10);
alert(ctrl2.x); //result 10

JavaScript in Control

CustomControl.MyControl = function(element) {
   CustomControl.MyControl.initializeBase (this, [element]);

   this.x = null;

}

CustomControl.MyControl.prototype = {
    set_x: function(value) {
          this.x = value;     
    } 
}

Note: I'm not sure of etiquitte for answering your own question. I will up-vote Chris's answer for helping me get to the right article. If there are other etiquiite rules I am happy to oblige.

Upvotes: 1

BigBlondeViking
BigBlondeViking

Reputation: 3963

You might need to use the dreaded eval() function to turn the string into JSON,

Here is a great post to help you on your way : Safely turning a JSON string into an object

Upvotes: 0

Related Questions