AJAX: Working with Properties

In JavaScript, there really isn't such as thing as properties.  Essentially a read/write property is represented by two methods, one with a "get_" prefix and one with a "set_" prefix.  However, the ASP.NET AJAX framework separates this as just a method; for instance, the following property definition is shown below:

//note the function declaration after is the prototype syntax, as properties are note
get_text : function()
{
  return this._text;
}

set_text : function(value)
{
  if (this._text != value)
  {
    this._text = value;
    this.raisePropertyChanged("text");
  }
}

In javascript, you can't reference the property via "text" and work with it like a property in .NET.  You have to use the get_text() and set_text("text") method calls; however, in .NET, you can work with it like a "text" property when you describe it.  Every ASP.NET AJAX server control needs to describe its client counterpart in the GetScriptDescriptors method; to describe a property can simply be done by:

descriptor.AddProperty("text", this.Text);

Notice the property doesn't need to specify "get_" or "set_" at all; it can simply reference it as "text" (the framework appends a "get_" or "set_" when it makes the actual assignment.  Also, the second parameter of AddProperty pushes down the current value of Text stored on the server-side, which acts as the initial value at load time.

If you use the AJAX Control Toolkit approach to developing custom controls or extenders you don't need to define GetScriptDescriptors; rather, the framework does it for you using reflection of attributes, shown below:

[
ExtenderControlProperty,
ClientScriptResource("text")
]
public string Text { .. }

ExtenderControlProperty notes that Text should be described as a property, while ClientScriptResources states what the property is named.  You don't need to use ClientScriptResource if the server-side property name matches the client side name, but the matching is case sensitive and our script uses lower camel case instead of upper as on the server, which is why I defiend the attribute.  At runtime, the previous descriptor.AddProperty statement is created automatically for us and the script is described correctly.

Published Thursday, July 17, 2008 8:00 PM by bmains
Filed under:

Comments

No Comments

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.