Welcome!

Agile Computing Authors: Astadia CloudGPS, Elizabeth White, Yeshim Deniz, Pat Romanski, Harry Trott

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
With tough new regulations coming to Europe on data privacy in May 2018, Calligo will explain why in reality the effect is global and transforms how you consider critical data. EU GDPR fundamentally rewrites the rules for cloud, Big Data and IoT. In his session at 21st Cloud Expo, Adam Ryan, Vice President and General Manager EMEA at Calligo, will examine the regulations and provide insight on how it affects technology, challenges the established rules and will usher in new levels of diligence...
The financial services market is one of the most data-driven industries in the world, yet it’s bogged down by legacy CPU technologies that simply can’t keep up with the task of querying and visualizing billions of records. In his session at 20th Cloud Expo, Karthik Lalithraj, a Principal Solutions Architect at Kinetica, discussed how the advent of advanced in-database analytics on the GPU makes it possible to run sophisticated data science workloads on the same database that is housing the rich...
"DX encompasses the continuing technology revolution, and is addressing society's most important issues throughout the entire $78 trillion 21st-century global economy," said Roger Strukhoff, Conference Chair. "DX World Expo has organized these issues along 10 tracks with more than 150 of the world's top speakers coming to Istanbul to help change the world."
DX World EXPO, LLC., a Lighthouse Point, Florida-based startup trade show producer and the creator of "DXWorldEXPO® - Digital Transformation Conference & Expo" has announced its executive management team. The team is headed by Levent Selamoglu, who has been named CEO. "Now is the time for a truly global DX event, to bring together the leading minds from the technology world in a conversation about Digital Transformation," he said in making the announcement.
SYS-CON Events announced today that Massive Networks 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. Massive Networks mission is simple. To help your business operate seamlessly with fast, reliable, and secure internet and network solutions. Improve your customer's experience with outstanding connections to your cloud.
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...
"The Striim platform is a full end-to-end streaming integration and analytics platform that is middleware that covers a lot of different use cases," explained Steve Wilkes, Founder and CTO at Striim, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
SYS-CON Events announced today that Calligo, an innovative cloud service provider offering mid-sized companies the highest levels of data privacy and security, 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. Calligo offers unparalleled application performance guarantees, commercial flexibility and a personalised support service from its globally located cloud plat...
Everything run by electricity will eventually be connected to the Internet. Get ahead of the Internet of Things revolution and join Akvelon expert and IoT industry leader, Sergey Grebnov, in his session at @ThingsExpo, for an educational dive into the world of managing your home, workplace and all the devices they contain with the power of machine-based AI and intelligent Bot services for a completely streamlined experience.
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.
SYS-CON Events announced today that Datera, that offers a radically new data management architecture, 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. Datera is transforming the traditional datacenter model through modern cloud simplicity. The technology industry is at another major inflection point. The rise of mobile, the Internet of Things, data storage and Big...
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
"We provide IoT solutions. We provide the most compatible solutions for many applications. Our solutions are industry agnostic and also protocol agnostic," explained Richard Han, Head of Sales and Marketing and Engineering at Systena America, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We are focused on SAP running in the clouds, to make this super easy because we believe in the tremendous value of those powerful worlds - SAP and the cloud," explained Frank Stienhans, CTO of Ocean9, Inc., in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"We've been engaging with a lot of customers including Panasonic, we've been involved with Cisco and now we're working with the U.S. government - the Department of Homeland Security," explained Peter Jung, Chief Product Officer at Pulzze Systems, in this SYS-CON.tv interview at @ThingsExpo, held June 6-8, 2017, at the Javits Center in New York City, NY.
"MobiDev is a Ukraine-based software development company. We do mobile development, and we're specialists in that. But we do full stack software development for entrepreneurs, for emerging companies, and for enterprise ventures," explained Alan Winters, U.S. Head of Business Development at MobiDev, in this SYS-CON.tv interview at 20th Cloud Expo, held June 6-8, 2017, at the Javits Center in New York City, NY.
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.
In his opening keynote at 20th Cloud Expo, Michael Maximilien, Research Scientist, Architect, and Engineer at IBM, discussed the full potential of the cloud and social data requires artificial intelligence. By mixing Cloud Foundry and the rich set of Watson services, IBM's Bluemix is the best cloud operating system for enterprises today, providing rapid development and deployment of applications that can take advantage of the rich catalog of Watson services to help drive insights from the vast t...
SYS-CON Events announced today that EnterpriseTech 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. EnterpriseTech is a professional resource for news and intelligence covering the migration of high-end technologies into the enterprise and business-IT industry, with a special focus on high-tech solutions in new product development, workload management, increased effic...
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...