ASP.NET Ajax Custom Controls
-
Upload
sampetruda -
Category
Documents
-
view
2.105 -
download
0
Transcript of ASP.NET Ajax Custom Controls
ASP.NET Ajax Custom Controls
Creating your own JavaScript-based, Ajax-enabled,
client-side controls
Overview
Custom ASP.NET Ajax controls
Components
Controls
Control extenders
Building server controls and components
Sys.UI.Control
Sys.UI.Behavior
IScriptControl
Embedding scripts as resources
Building extender controls
System.Web.UI.ExtenderControl
TargetControlID, TargetControlType attribute
Custom ASP.NET Ajax Controls
There are three distinct types of Ajax custom controls you
might build
Non-visible components
Visible components (controls)
Control extenders
All three are similar to build
Incorporate JavaScript into control rendering
Integrate with page ScriptManager
Use ScriptDescriptors to describe client properties/events
IScriptControl
Core interface for integrating with ASP.NET Ajax
Include script references with GetScriptReferences
Add property/event descriptors to automatically wire up to client controls
namespace System.Web.UI{
public interface IScriptControl{
IEnumerable<ScriptDescriptor> GetScriptDescriptors();IEnumerable<ScriptReference> GetScriptReferences();
}}
Sample: Custom TextBox
Consider a custom TextBox derivative that highlights on focus:
<head runat="server"><style type="text/css">.LowLight {background-color:#EEEEEE;}.HighLight {background-color:Ivory; }
</style></head><body><form id="form1" runat="server"><div><asp:ScriptManager ID="ScriptManager1" runat="server" />
<ps:SampleTextBox ID="TextBox1" runat="server" NoHighlightCssClass="LowLight" HighlightCssClass="HighLight" />
...
1) Create client Sys.Web.UI derivative
Type.registerNamespace('PS');
PS.SampleTextBox = function(element) { PS.SampleTextBox.initializeBase(this, [element]);
this._highlightCssClass = null;this._nohighlightCssClass = null;
}PS.SampleTextBox.prototype = {
initialize : function() {PS.SampleTextBox.callBaseMethod(this, 'initialize');
...}, ...}
PS.SampleTextBox.registerClass('PS.SampleTextBox', Sys.UI.Control);
client-side
2) Define server-side Control derivative
namespace PS{public class SampleTextBox : TextBox, IScriptControl{private string _highlightCssClass;private string _noHighlightCssClass;private ScriptManager sm;
public string HighlightCssClass{get { return _highlightCssClass; }set { _highlightCssClass = value; }
}
public string NoHighlightCssClass{get { return _noHighlightCssClass; }set { _noHighlightCssClass = value; }
}// continued…
server-side
3) Implement IScriptControl
public IEnumerable<ScriptReference> GetScriptReferences(){ScriptReference reference = new ScriptReference();reference.Path = ResolveClientUrl("CustomTextBox.js");
yield return reference;}
public IEnumerable<ScriptDescriptor> GetScriptDescriptors(){ScriptControlDescriptor descriptor =
new ScriptControlDescriptor("PS.SampleTextBox", this.ClientID);descriptor.AddProperty("highlightCssClass", this.HighlightCssClass);descriptor.AddProperty("nohighlightCssClass", this.NoHighlightCssClass);
yield return descriptor;}
Sys.Application.initialize();
Sys.Application.add_init(
function() { $create(PS.SampleTextBox,
{"highlightCssClass":"HighLight","nohighlightCssClass":"LowLight"},
null, null, $get("TextBox1")); });
<script src="/TestClient/CustomTextBox.js" type="text/javascript"></script>
4) Integrate with ScriptManager
protected override void OnPreRender(EventArgs e){if (!this.DesignMode){
sm = ScriptManager.GetCurrent(Page);if (sm == null)
throw new HttpException("Missing ScriptManager ");sm.RegisterScriptControl(this);
}
base.OnPreRender(e);}
protected override void Render(HtmlTextWriter writer){if (!this.DesignMode)
sm.RegisterScriptDescriptors(this);
base.Render(writer);}
5) Build control with client integration
Standard techniques for building controls apply
All script interaction can leverage ASP.NET Ajax
get_element() inherited from Sys.UI.Control gives you access to the
rendered HTML element in the client
Use pageLoad( ) to hook initialization
Leverage remaining Sys.* classes as needed
Bundling compiled resources
ASP.NET 2.0 introduces a new handler, new attributes access,
& bundle resources in assemblies
WebResource.axd — serves objects from an assembly's resources
[assembly:WebResource(...)] — annotates an assembly for proper
WebResource.axd retrieval
Page.ClientScript.GetWebResourceUrl returns WebResource.axd url
with query string to return a specific resource
Ideal for custom controls that need to embed images /
JavaScript to simplify deployment
Example — resource bundling
[assembly: WebResource("StopLightControl.YellowOn.jpg", "image/jpg")][assembly: WebResource("StopLightControl.YellowDim.jpg", "image/jpg")]
Page.ClientScript.GetWebResourceUrl(GetType(), "StopLightControl.YellowOn.jpg");
WebResource.axd?d=lZ...kSq0&t=632579866277167200
Compile action set to
Embedded Resource
ScriptReference
To reference resource-embedded script files:
Include WebResource assembly-level attribute to expose
Implement GetScriptReferences with alternate ctor of ScriptReference
class
[assembly: WebResource("AjaxCustomControls.CustomTextBox.js", "text/javascript")]
public IEnumerable<ScriptReference> GetScriptReferences(){ScriptReference reference =
new ScriptReference("AjaxCustomControls.CustomTextBox.js",GetType().Assembly.FullName);
return new ScriptReference[] { reference };}
ScriptResource
ASP.NET Ajax supports string resources as embedded
resources
Useful for localizing strings in your client script files
Steps for using ScriptResource
1. Create a .resx file in your project, with Build Action set to Embedded
Resource
2. Add strings to .resx you want to reference in your client script
3. Add an assembly-level attribute declaration of ScriptResource
4. Reference strings with typename string passed in a last parameter to
ScriptResource attribute
Using ScriptResource
[assembly: ScriptResource("HoverImageControl.HoverImageControl.js","HoverImageControl.HoverImageControl", "HoverImageControl.Resource")]
_onMouseDown : function(e) {if (this.get_element() && !this.get_element().disabled) {
this.get_element().src = this._clickImageUrl;alert(HoverImageControl.Resource.hi);
}},
HoverImageControl.js
Name of embedded script that will use resource
Name of embedded resource
Script typename you will use to extract strings
Reference resource
strings with typename
ScriptResource Implementation
The effect of using ScriptResource is to modify the referenced
embedded script to include a class that provides all string .resx
values
No server communication to retrieve values
Simple integration with existing script files
Resource file loading is culture-dependent
Set UICulture="auto" and Culture="auto" on your .aspx page to have
culture set based on user language preference
Create additional copies of .resx file with locale name (like
mystrings.fr.resx)
Type.registerNamespace('HoverImageControl');HoverImageControl.Resource={"hi":"Hello there!","bye":"Good bye!"};
Appended to script file
Building components
Differences when building components instead of controls
Return ScriptComponentDescriptor from GetScriptDescriptors
Inherit client-side class from Sys.UI.Component
Extender controls
Extender controls are designed to extend other controls
Control does not render separately
Inherit server-control from System.Web.UI.ExtenderControl
Implement IScriptControl, exposing as virtual methods
Define TargetControlID property
Inherit client behavior from Sys.UI.Behavior
<asp:TextBox ID="TextBox1" runat="server" />
<ps:FocusBehavior ID="FocusExtender1" runat="server"NoHighlightCssClass="LowLight"HighlightCssClass="HighLight"TargetControlID="TextBox1" />
Summary
Custom controls are the building blocks for extending ASP.NET
Ajax
Components
Controls
Control Extenders
All provide tight integration with ScriptManager and client-side
script support
© 2008 Pluralsight, LLC
References
Online documentation:
http://asp.net/ajax/documentation/live/
Books:
“ASP.NET Ajax in Action”, by A Gallo, D. Barkol and R. Vavilala (Manning
Pub)