Welcome!

Agile Computing Authors: Pat Romanski, Larry Alton, Elizabeth White, Dean Madison, Astadia CloudGPS

Related Topics: Agile Computing, Microsoft Cloud

Agile Computing: Article

A Sneak Peak at ASP.NET AJAX 4.0’s Client-Side Templating

I just want to reiterate how happy I am with the transparency of the ASP.NET team lately

Dave Ward's "Encosia" Blog

Hot on the heels of the recent ASP.NET AJAX roadmap, Bertrand and team have released a limited preview of the new AJAX functionality coming in ASP.NET 4.0.

To see how the new functionality stacks up, I decided to recreate my recent jTemplates example, using only ASP.NET AJAX and its new templating features. Eventually, I settled on using the DataView class, which offers more advanced, repeater-like functionality.

Having successfully completed the exercise, I thought it seemed like something that you might find interesting too. The solution boils down to four easy steps:

  • Creating a page method to return JSON data.
  • Setting up a ScriptManager to coordinate script and page method access.
  • Defining the client-side template that will render the JSON data.
  • Using JavaScript to render the template, using the page method’s return.

A familiar page method

The first order of business is obtaining a data source to render. To keep things simple, let’s reuse the RSS reader from my jQuery “repeater” example:

[WebMethod]
public static IEnumerable GetFeedburnerItems()
{
XDocument feedXML =
XDocument.Load("http://feeds.encosia.com/Encosia");

var feeds =
from feed in feedXML.Descendants("item")
select new
{
Date = DateTime.Parse(feed.Element("pubDate").Value)
.ToShortDateString(),
Title = feed.Element("title").Value,
Link = feed.Element("link").Value,
Description = feed.Element("description").Value
};

return feeds;
}

This page method will return a JSON array representing the latest ten items from my RSS feed. Specifically, their Date, Title, Link, and Description.

Setting up the ScriptManager

The ASP.NET AJAX 4.0 templating features depend on functionality in the ASP.NET AJAX client side framework. We could include MicrosoftAjax.js manually, but since we’re also using a page method, the ScriptManager will serve our needs well:

<asp:ScriptManager runat="server" EnablePageMethods="true">
<Scripts>
<asp:ScriptReference Path="~/MicrosoftAjaxTemplates.js" />
<asp:ScriptReference Path="~/default.js" />
</Scripts>
</asp:ScriptManager>

EnablePageMethods will generate a JavaScript proxy for calling our page method. This is not necessarily the only or most efficient way of calling page methods, but works well enough for our purposes here.

Creating the template

Next, we need to define a template to render the page method’s return upon. The ASP.NET AJAX 4.0 templating engine’s syntax is very straightforward:

<table>
<thead>
<tr>
<th>Date</th>
<th>Title</th>
<th>Excerpt</th>
</tr>
</thead>
<tbody id="RSSItem" class="sys-template">
<tr>
<td>{{ Date }}</td>
<td><a href="{{ Link }}">{{ Title }}</a></td>
<td>{{ Description }}</td>
</tr>
</tbody>
</table>

The bracketed field names correspond to the names of the properties in the anonymous type generated by the page method. It couldn’t be much easier.

You may have noticed the sys-template CSS class applied to the meat of the template. This is a convention for hiding the template until it has been rendered. The class should be defined somewhere as:

.sys-template { display: none; visibility: hidden; }

During the rendering process, the templating engine will automatically attempt to remove the sys-template class, making the final result visible.

Bringing it all together

Now that we’ve got our JSON data source and have defined our template, the final step is simply to connect those dots.

Sys.Application.add_init(AppInit);

// Execute the page method when the page finishes loading.
function AppInit(sender, args) {
PageMethods.GetFeedburnerItems(OnSuccess, OnFailure);
}

function OnSuccess(result) {
// Create an ASP.NET AJAX 4.0 DataView, targeted at our template.
var dv = new Sys.Preview.UI.DataView($get('RSSItem'));

// Pass the DataView our JSON result of RSS items to render.
dv.set_data(result);

// Render the DataView template, using the provided JSON array.
dv.render();
}

// Do not do this in production code!
function OnFailure() { }

The OnSuccess function is where all of the magic happens. When the page method completes its execution, three things happen:

  • A DataView object is created for our template, by passing its containing DomElement: $get(’RSSItem’).
  • The JSON result is assigned to the DataView, using its set_data method.
  • The DataView’s render method is called to generate the end result.

Conclusion and a couple suggestions.

Comparing this implementation to my identical jTemplates example, I must say that I prefer the DataView solution. The syntax is impressively cleaner.

I just want to reiterate how happy I am with the transparency of the ASP.NET team lately. For those of us who aren’t MVPs or ASPInsiders, it’s nice to have a chance to offer constructive feedback and generally not be left in the dark.

In that spirit, I have two suggestions to improve the templating engine.

External templates. I don’t particularly enjoy mingling my template with the rest of the page’s HTML. This is one thing that jTemplates handles very well, with its createTemplateURL method. I would love to see this functionality in the ASP.NET AJAX templating engine and/or the DataView class.

To one-up jTemplates, it would be fantastic if there were a way to pre-load the template. During the second or two that the AJAX call executes would be an excellent time to get the template ready, so that there’s no HTTP delay after the data is ready.

Table issues. Ideally, there should be an automatic convention for hiding the entire table until the template is rendered. Maybe that’s already possible, but I wasn’t able to find a configuration that would do that while repeating only the tbody.

It would make sense if we could assign the entire table a CSS class of sys-template, which would be removed if any of its children were a template being rendered. I usually avoid special cases like this, but I expect that the table scenario will be a prevalent one. It makes sense to optimize for it.

Try it for yourself

Download Source:  dataview-demo.zip (12kb)

 

More Stories By Dave Ward

Dave Ward wrote his first computer program in 1981, using good ‘ol Microsoft Color BASIC and cassette tapes for data storage. Over the years since then, he has had the opportunity to work on projects ranging from simple DOS applications to global telecommunications networks spanning multiple platforms.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
The Internet giants are fully embracing AI. All the services they offer to their customers are aimed at drawing a map of the world with the data they get. The AIs from these companies are used to build disruptive approaches that cannot be used by established enterprises, which are threatened by these disruptions. However, most leaders underestimate the effect this will have on their businesses. In his session at 21st Cloud Expo, Rene Buest, Director Market Research & Technology Evangelism at Ara...
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
Internet of @ThingsExpo, taking place October 31 - November 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 21st Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devic...
Mobile device usage has increased exponentially during the past several years, as consumers rely on handhelds for everything from news and weather to banking and purchases. What can we expect in the next few years? The way in which we interact with our devices will fundamentally change, as businesses leverage Artificial Intelligence. We already see this taking shape as businesses leverage AI for cost savings and customer responsiveness. This trend will continue, as AI is used for more sophistica...
SYS-CON Events announced today that SourceForge has been named “Media Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. SourceForge is the largest, most trusted destination for Open Source Software development, collaboration, discovery and download on the web serving over 32 million viewers, 150 million downloads and over 460,000 active development projects each and every month.
SYS-CON Events announced today that DXWorldExpo has been named “Global Sponsor” of SYS-CON's 21st International Cloud Expo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Digital Transformation is the key issue driving the global enterprise IT business. Digital Transformation is most prominent among Global 2000 enterprises and government institutions.
Elon Musk is among the notable industry figures who worries about the power of AI to destroy rather than help society. Mark Zuckerberg, on the other hand, embraces all that is going on. AI is most powerful when deployed across the vast networks being built for Internets of Things in the manufacturing, transportation and logistics, retail, healthcare, government and other sectors. Is AI transforming IoT for the good or the bad? Do we need to worry about its potential destructive power? Or will we...
SYS-CON Events announced today that SIGMA Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. uLaser flow inspection device from the Japanese top share to Global Standard! Then, make the best use of data to flip to next page. For more information, visit http://www.sigma-k.co.jp/en/.
SYS-CON Events announced today that Daiya Industry will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Daiya Industry specializes in orthotic support systems and assistive devices with pneumatic artificial muscles in order to contribute to an extended healthy life expectancy. For more information, please visit https://www.daiyak...
SYS-CON Events announced today that B2Cloud will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. B2Cloud specializes in IoT devices for preventive and predictive maintenance in any kind of equipment retrieving data like Energy consumption, working time, temperature, humidity, pressure, etc.
SYS-CON Events announced today that Massive Networks, that helps your business operate seamlessly with fast, reliable, and secure internet and network solutions, has been named "Exhibitor" of SYS-CON's 21st International Cloud Expo ®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. As a premier telecommunications provider, Massive Networks is headquartered out of Louisville, Colorado. With years of experience under their belt, their team of...
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp em...
SYS-CON Events announced today that Interface Corporation will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Interface Corporation is a company developing, manufacturing and marketing high quality and wide variety of industrial computers and interface modules such as PCIs and PCI express. For more information, visit http://www.i...
SYS-CON Events announced today that Mobile Create USA will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Mobile Create USA Inc. is an MVNO-based business model that uses portable communication devices and cellular-based infrastructure in the development, sales, operation and mobile communications systems incorporating GPS capabi...
SYS-CON Events announced today that Nihon Micron will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Nihon Micron Co., Ltd. strives for technological innovation to establish high-density, high-precision processing technology for providing printed circuit board and metal mount RFID tags used for communication devices. For more inf...
SYS-CON Events announced today that Suzuki Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Suzuki Inc. is a semiconductor-related business, including sales of consuming parts, parts repair, and maintenance for semiconductor manufacturing machines, etc. It is also a health care business providing experimental research for...
While some developers care passionately about how data centers and clouds are architected, for most, it is only the end result that matters. To the majority of companies, technology exists to solve a business problem, and only delivers value when it is solving that problem. 2017 brings the mainstream adoption of containers for production workloads. In his session at 21st Cloud Expo, Ben McCormack, VP of Operations at Evernote, will discuss how data centers of the future will be managed, how th...
SYS-CON Events announced today that Ryobi Systems will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ryobi Systems Co., Ltd., as an information service company, specialized in business support for local governments and medical industry. We are challenging to achive the precision farming with AI. For more information, visit http:...
SYS-CON Events announced today that MIRAI Inc. will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. MIRAI Inc. are IT consultants from the public sector whose mission is to solve social issues by technology and innovation and to create a meaningful future for people.
SYS-CON Events announced today that mruby Forum will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. mruby is the lightweight implementation of the Ruby language. We introduce mruby and the mruby IoT framework that enhances development productivity. For more information, visit http://forum.mruby.org/.