Welcome!

Agile Computing Authors: Liz McMillan, Yeshim Deniz, Ed Featherston, Pat Romanski, Elizabeth White

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
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
Charles Araujo is an industry analyst, internationally recognized authority on the Digital Enterprise and author of The Quantum Age of IT: Why Everything You Know About IT is About to Change. As Principal Analyst with Intellyx, he writes, speaks and advises organizations on how to navigate through this time of disruption. He is also the founder of The Institute for Digital Transformation and a sought after keynote speaker. He has been a regular contributor to both InformationWeek and CIO Insight...
Gemini is Yahoo’s native and search advertising platform. To ensure the quality of a complex distributed system that spans multiple products and components and across various desktop websites and mobile app and web experiences – both Yahoo owned and operated and third-party syndication (supply), with complex interaction with more than a billion users and numerous advertisers globally (demand) – it becomes imperative to automate a set of end-to-end tests 24x7 to detect bugs and regression. In th...
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
"Evatronix provides design services to companies that need to integrate the IoT technology in their products but they don't necessarily have the expertise, knowledge and design team to do so," explained Adam Morawiec, VP of Business Development at Evatronix, in this SYS-CON.tv interview at @ThingsExpo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
The Founder of NostaLab and a member of the Google Health Advisory Board, John is a unique combination of strategic thinker, marketer and entrepreneur. His career was built on the "science of advertising" combining strategy, creativity and marketing for industry-leading results. Combined with his ability to communicate complicated scientific concepts in a way that consumers and scientists alike can appreciate, John is a sought-after speaker for conferences on the forefront of healthcare science,...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
Explosive growth in connected devices. Enormous amounts of data for collection and analysis. Critical use of data for split-second decision making and actionable information. All three are factors in making the Internet of Things a reality. Yet, any one factor would have an IT organization pondering its infrastructure strategy. How should your organization enhance its IT framework to enable an Internet of Things implementation? In his session at @ThingsExpo, James Kirkland, Red Hat's Chief Archi...
The current age of digital transformation means that IT organizations must adapt their toolset to cover all digital experiences, beyond just the end users’. Today’s businesses can no longer focus solely on the digital interactions they manage with employees or customers; they must now contend with non-traditional factors. Whether it's the power of brand to make or break a company, the need to monitor across all locations 24/7, or the ability to proactively resolve issues, companies must adapt to...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
DXWorldEXPO LLC announced today that the upcoming DXWorldEXPO | CloudEXPO New York event will feature 10 companies from Poland to participate at the "Poland Digital Transformation Pavilion" on November 12-13, 2018.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
The best way to leverage your CloudEXPO | DXWorldEXPO presence as a sponsor and exhibitor is to plan your news announcements around our events. The press covering CloudEXPO | DXWorldEXPO will have access to these releases and will amplify your news announcements. More than two dozen Cloud companies either set deals at our shows or have announced their mergers and acquisitions at CloudEXPO. Product announcements during our show provide your company with the most reach through our targeted audienc...
JETRO showcased Japan Digital Transformation Pavilion at SYS-CON's 21st International Cloud Expo® at the Santa Clara Convention Center in Santa Clara, CA. The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
@DevOpsSummit at Cloud Expo, taking place November 12-13 in New York City, NY, is co-located with 22nd international CloudEXPO | first international DXWorldEXPO and will feature technical sessions from a rock star conference faculty and the leading industry players in the world.