Thursday, July 23, 2009

Asp.Net Ajax Extender Control Tutorial

I built several Extender Control and Script Control in my provious posts within PainControls assembly, which you can download. You can search the resource about how to build extender control or script control on web. However, I'd still like to write something on it in my words. If you are interesting on that, you can check this article.

Microsoft ASP.Net Ajax Extensions enables you to expand the capabilities of an ASP.Net Web Application in order to create a rich client user experience. We can make use of ScriptControl or ExtenderControl to build a rich client behavior or web control. The difference between ExtenderControl and ScriptControl is that Extender is used on creating client script capabilities on an existing control, which is called "TargetControl" for this behavior, whereas ScriptControl is an absolute web control which contains rich client functionality. For example, when we'd like to build a ModalPopup which will pop out an existing Panel, show/hide functionality is the client script application, then we can build it as ExtenderControl. However, for ScriptControl, for instance, TabContainer which is the entirely new web control contains the client script functionality, so we can build it as ScriptControl.

1. To encapsulate the client behavior for use by ASP.NET page developers, you can use an extender control. An extender control is a Web server control that inherits the ExtenderControl abstract class in the System.Web.UI namespace.
Extender control is used for client script functionality extension of an existing web control. It can be applied to specific Web server control types. You identify the types of Web server controls to which an extender control can be applied by using the TargetControlTypeAttribute attribute.
(The sample code as below is according to the TimePicker which is from http://vincexu.blogspot.com/2009/07/ajax-timepickerclockpicker-control.html)

[TargetControlType(typeof(Control))]
public class TimePicker: ExtenderControl

2. The following two methods of the ExtenderControl abstract class that you must implement in an extender control.

protected override IEnumerable GetScriptDescriptors(Control targetControl)
{
ScriptControlDescriptor descriptor = new ScriptControlDescriptor("PainControls.TimePicker", targetControl.ClientID);
descriptor.AddElementProperty("errorSpan", this.NamingContainer.FindControl(ErrorPresentControlID).ClientID);
descriptor.AddProperty("timeType", TimeType);
descriptor.AddEvent("showing", OnClientShowing);
yield return descriptor;

}
protected override IEnumerable GetScriptReferences()

{
yield return new ScriptReference(Page.ClientScript.GetWebResourceUrl(this.GetType(), "PainControls.TimePicker.TimePicker.js"));
}

3. Embed Css reference in PreRender phase.

private void RenderCssReference()
{
string cssUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "PainControls.TimePicker.TimePicker.css");
HtmlLink link = new HtmlLink();

link.Href = cssUrl;
link.Attributes.Add("type", "text/css");
link.Attributes.Add("rel", "stylesheet");
Page.Header.Controls.Add(link);
}

4. Set all resources(contain images, css file and js file) embedded in this extender control as "Embedded Resource"(property "Build Action").

5. This extender control can derive from IExtenderControl interface and a server control, instead of ExtenderControl if you'd like to.

The control can derive from other server controls if you want to make it inherit a server control than ExtenderControl. In this scenario, it should derive from IExtenderControl interface and a server control class. Meanwhile, we have another three steps need to do:
1) Define TargetControl property
2) Override OnPreRender method. Register the web control as the ExtenerControl in OnPreRender phase.
ScriptManager manager = ScriptManager.GetCurrent(this.Page);
if (manager == null)
{
throw new InvalidOperationException("A ScriptManager is required on the page.");
}
manager.RegisterExtenderControl(this);
3) Override Render method. Register the script descriptor which has been defined.
ScriptManager.GetCurrent(this.Page).RegisterScriptDescriptors(this);

6. The rest work is on client-side. Register client NameSpace first.

Type.registerNamespace("PainControls");

7. Build client class.

PainControls.TimePicker = function(element)
{
}
PainControls.TimePicker.prototype = {
}


8. Register the class that inherits "Sys.UI.Behavior".

PainControls.TimePicker.registerClass('PainControls.TimePicker', Sys.UI.Behavior);

9. Call base method in constructor method

PainControls.TimePicker.initializeBase(this, [element]);

10. Implementing the Initialize and Dispose Methods.
Build "initialize" and "dispose" method in prototype of the class. The initialize method is called when an instance of the behavior is created. Use this method to set default property values, to create function delegates, and to add delegates as event handlers. The dispose method is called when an instance of the behavior is no longer used on the page and is removed. Use this method to free any resources that are no longer required for the behavior, such as DOM event handlers.

initialize: function() {
PainControls.TimePicker.callBaseMethod(this, 'initialize');
},
dispose: function() {

PainControls.TimePicker.callBaseMethod(this, 'dispose');
}

11. Defining the Property Get and Set Methods.
Each property identified in the ScriptDescriptor object of the extender control's GetScriptDescriptors(Control) method must have corresponding client accessors. The client property accessors are defined as get_<:property> and set_<:property> methods of the client class prototype.

get_timeType: function() {
return this._timeType;
},
set_timeType: function(val) {

if (this._timeType !== val) {
this._timeType = val;
this.raisePropertyChanged('timeType');
}
},

12. Defining the Event Handlers for the DOM Element
1) Defining the handler in constructor function:
this._element_focusHandler = null;
2) Associate the handler with the DOM Element event in initailize method:
this._element_focusHandler = Function.createDelegate(this, this._element_onfocus);
3) Add the handler in initailize method:
$addHandler(this.get_element(), 'focus', this._element_focusHandler)
4) Build callback method about this event:
_element_onfocus:function(){
}


13. Defining the Event Handlers for the behavior
Each event identified in the ScriptDescriptor object of the extender control's GetScriptDescriptors(Control) method must have corresponding client accessors. The client event accessors are defined as add_<:event> and remove_<:event> methods of the client class prototype. The method Raise<:event> is defined to trigger the event.

add_showing: function(handler) {
this.get_events().addHandler("showing", handler);
},
remove_showing: function(handler) {
this.get_events().removeHandler("showing", handler);

},
raiseShowing: function(eventArgs) {
var handler = this.get_events().getHandler('showing');

if (handler) {
handler(this, eventArgs);
}
},

14. Use this extender control TimePicker in page.
1) Register the assembly in page.


<%@ Register TagPrefix="PainControls" Assembly="PainControls" Namespace="PainControls" %>


2) Add a ScriptManager control in page, and create TimePicker control to bind on a TextBox.


<asp:textbox id="TextBox1" runat="server" text=""></asp:textbox>
<PainControls:timepicker id="t1" runat="server" targetcontrolid="TextBox1" timetype="H24">

3 comments:

Vince said...

I have been in search of such interesting Articles, I am on a holiday its good to see that everyone are trying their best to keep up

the Spirit by having such great articles posted.

Cheers, Keep it up.

___________________
Vince
Online Marketing of your brand

r4 nintendo ds said...

Very useful. I had downloaded AJAX toolkit a month ago, but was not aware of its all features. This helped me a lot. Thank you very much.

Maxi Ng said...

I would love to code an extender too.
But I think your article only tells us steps to code without mentioning their purposes.
if you are writing it as a note for yourself, then just ignore me.
I am without a clue how to make extender control after reading this article.
like 1) Define TargetControl property, how do I do this?
maybe you can have another post that gives a little background.

But, Thank you. Good work.