The ASP.NET team heard feedback from the community that many
developers preferred an imperative code approach (as opposed to a declarative
syntax approach) when creating client controls. With today’s release we are
introducing a simple imperative code syntax for creating client controls and
binding them to HTML elements within a page. This syntax is fully supported by
the JavaScript Intellisense in both VS 2008 and VS 2010.
Below is an example of the imperative code you can now write
to programmatically create a client-side DataView control that displays data
from a WCF web service:
Figure 1
The above code instantiates a new Microsoft
Ajax DataView control and attaches the control to an HTML <div> element
with the id “imageView”. The URL of the WCF service is specified with the
“dataProvider” property, and the name of the method to call on the service is
specified with the “fetchOperation” property. The “autoFetch” property
indicates that the control should automatically bind against the WCF service
when it loads.
Below is what the “imageView” HTML <div>
element that the DataView control is attached to looks like. This
<div> contains a template that will be used for displaying each data item
retrieved from the service (note: templates were a feature we introduced with
an earlier Microsoft Ajax Preview release):
Figure 2
The {{ Uri }} and {{ Name }} expressions
within the template above are replaced with the Name and Uri properties of the
images retrieved from the service. The attribute namespace prefix
“sys:src” on the <img> element is used to prevent browsers from
attempting to load an image at the actual path {Uri}. The value of the sys:src
attribute gets plugged into the src attribute when the template is loaded.
When the page is rendered in the browser, we
then get a simple photo gallery like below:
Figure 3
Alternatively, if you don’t want to use a
declarative binding syntax within a template, you can modify the template to be
pure HTML markup like below (no more {{ }} expressions):
Figure 4
You can then wire-up and specify a
itemRendered event handler when you create the DataView control like below:
Figure 5
You can then implement the “imageRendered”
event handler using the JavaScript below, and use the Sys.bind() method to
programmatically assign values to the <img> and <span> tags within
the template:
Figure 6
This allows you to maintain your template as pure HTML
markup, while still displaying the same photo gallery experience at runtime.