Browser Side Templating With Asp.Net 4.0 Ajax

53
Browser Side Templating {BST} with ASP.NET 4.0 AJAX Shahriar Hyder Kaz Software Ltd.

description

The goal of the seminar is to talk about ‘Browser Side Templating’ (BST) pattern. It is also known as client side templating pattern in some quarters. The idea is to implement ‘client side templates’ ala ASP.NET GridView templates and ‘client side data binding’ features inside HTML through JavaScript with the help of ‘pure AJAX’ at times. I would like to start off by describing the pattern and why we really need it. At the same time I would also concentrate on giving you a glimpse of the challenges for implementing this pattern. Lastly, I would be showing you few demos that uses browser side templating with ASP.NET AJAX 4.0 after talking about some of the new features that have been integrated into the framework to accomplish so.

Transcript of Browser Side Templating With Asp.Net 4.0 Ajax

Page 1: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating {BST} with ASP.NET 4.0 AJAX

Shahriar HyderKaz Software Ltd.

Page 2: Browser Side Templating With Asp.Net 4.0 Ajax

Understand what AJAX isShow how Microsoft AJAX is being used todayUnderstand the “pure” AJAX modelDescribe the BST PatternKeeping the challenges for BST in mindIntroduce the new features in ASP.NET AJAX 4.0 for BST (client data, client templates, declarative markup, bindings, command bubbling, etc.)Demo. Yea Now you should have no complaint!

Objectives And Takeaways

Page 3: Browser Side Templating With Asp.Net 4.0 Ajax

What Is AJAX All About?Server AJAX versus "pure" AJAX

Initial request: HTML

HTMLForm POST

HTML + JSON

JSONJSON

Renderin

g

Rendering

Server AJAX

“Pure” AJAX

Page 4: Browser Side Templating With Asp.Net 4.0 Ajax

UpdatePanelServer Controls and ExtendersDevelopers shielded from JavaScriptClient-focused development possible but less familiar

 Microsoft AJAX in .NET 4.0A server-side focus

Page 5: Browser Side Templating With Asp.Net 4.0 Ajax

Server-Side ASP.NET AJAXBenefits

Safe: No Browser Compatibility IssuesPowerful: Use any programming languageCompatible: Retrofit existing ASP.NET applications

DrawbacksResponsiveness: User must wait for a PostBack (no simultaneous Ajax)Performance: (most) page content must be rendered for each interactionFull Page Life Cycle FiresEven if UpdateMode Conditional UP events fire

Page 6: Browser Side Templating With Asp.Net 4.0 Ajax

It's all about the standard browserNo plug-in necessaryNetwork payload is way smaller(data < HTML, no ViewState round-tripping)More reactive UI

The “Pure AJAX” ModelWhy it matters

Page 7: Browser Side Templating With Asp.Net 4.0 Ajax

 Microsoft AJAX in .NET 4.0 “Pure AJAX” - much easier

Dynamic Client-Rendered UI the easy way

Server provides JSON Data, not HTMLClient data sourcesClient Templates for rendering UIDeclarative instantiation of Client ControlsJavaScript Objects and Arrays as live “observable” DataLive bindings

Page 8: Browser Side Templating With Asp.Net 4.0 Ajax

Data Sources: Client DataFrom Web services to plain JavaScript data

Plain JavaScript data: Arrays and objectsAny JSON Web service

ASMX Web ServicesWCF Web ServicesHTTP HandlersASP.NET MVC JSONResultREST Services.NET RIA Services

ADO.NET Data ServicesDataSource controlServer data gets represented on the client as plain JavaScript objects

Page 9: Browser Side Templating With Asp.Net 4.0 Ajax

Client Templates Simple rendering on the client

On the server:

<ItemTemplate runat="server"> <li><%# Eval("Name") %></li></ItemTemplate>

 On the client:

<ul class="sys-template"> <li>{{ Name }}</li></ul>

Page 10: Browser Side Templating With Asp.Net 4.0 Ajax

JSONJSON (JavaScript Object Notation) – is a light weight data interchange format.  It

essentially is composed of key-value pairs.  For Example –

XML

<rss version="2.0">  <channel>    <item>      <link>http://test.com</link>      <title>Page Title</title>    </item>  </channel></rss>

JSON  - {   "Version":"2.0",   "Channel": {         "Items": [{               "Link":"http://test.com",               "Title":"Page Title"          }]       }}

Page 11: Browser Side Templating With Asp.Net 4.0 Ajax

JSONThe beauty of JSON is it integrates easily with Javascript. Just use eval() function of JavaScript to parse. So to initialize the above JSON this should do the trick –

var rss = eval(‘({ "Version":"2.0", "Channel": { "Items": [{Link":"http://test.com",Title":"Page Title" }]}}’);

Javascript does provide some level of Object orientation. So you could access the properties from the above object like –

var itemtitle = rss.Channel.Items[0].Title;var rssVersion = rss.Version;

Page 12: Browser Side Templating With Asp.Net 4.0 Ajax

Server-centric AJAX Containers {ASP.NET AJAX

UpdatePanel}Ease of use: The most obvious advantage of this approach is that it is extremely easy to implement. It is really not much harder than building a vanilla postback-based ASP.NET application and then wrapping certain areas of the page with UpdatePanels. This approach is ideal for quickly adding AJAX features to existing ASP.NET applications.

Performance: The biggest downside of this approach is performance. UpdatePanels always post the entire page - including full ViewState - to the server. Even though the required AJAX update to the page is often minimal, its server-side page processing essentially takes the same resources as when doing a full postback. The response sends raw HTML back to the browser, adding kilobytes to the required network traffic to process the AJAX request. Even without ViewState, HTML isn't necessarily the most compact representation of your data.

Page 13: Browser Side Templating With Asp.Net 4.0 Ajax

Server-centric AJAX Containers {ASP.NET AJAX

UpdatePanel}Elegance: The server-centric AJAX container technique is fairly elegant from the implementation point of view. Page areas are cleanly wrapped by UpdatePanel instances and AJAX updates are accomplished by mapping server-side events to triggers. All AJAX magic is performed by the UpdatePanel control itself.

Features: All features exposed to the developer using the UpdatePanel control are entirely on the server side. The control was not designed to be driven by client-side logic. The server-centric approach lacks the finer level of control on the client, which is definitely needed to build sophisticated AJAX apps with hyper-responsive user interfaces.

Page 14: Browser Side Templating With Asp.Net 4.0 Ajax

Server-centric AJAX Containers {ASP.NET AJAX

UpdatePanel}Limits of Partial Rendering

The heaviness and waste of an entire page lifecycle on each async postback, combined with the limitations of the postback model itself made it useful only in certain situations (like removing the flicker from an existing website with heavy postbacks).

Page 15: Browser Side Templating With Asp.Net 4.0 Ajax

Server-centric AJAX Containers {ASP.NET AJAX

UpdatePanel}What makes partial rendering particularly appealing for the development of ASP.NET AJAX applications is its inherent simplicity—lower impact on existing pages and fewer demands on developers' skills. But partial rendering is merely a trick to bypass the browser in the execution of the postback request. Pages that use partial rendering are not truly AJAX pages because they still rely on the old postback method. But what does it mean to be a real AJAX application?

Page 16: Browser Side Templating With Asp.Net 4.0 Ajax

Server-centric AJAX Containers {ASP.NET AJAX

UpdatePanel}Essentially, a true AJAX application uses the XMLHttpRequest object to bypass the browser and establish direct communication with the Web server and any hosted HTTP endpoints. The application is capable of asynchronously retrieving necessary data and independently refreshing blocks of the user interface. Based on this key behavior, a number of AJAX frameworks have been designed that have different doses of syntactic sugar, larger or smaller feature sets, and richer or simpler families of user interface widgets. ASP.NET AJAX is one of these frameworks.

Page 17: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

It's important to note that there is a lot more to templates than just inserting data into placeholders in an HTML string. First, a template engine must have some sort of expression language to go beyond the simple field insertion. Second, it should enable scenarios of conditional rendering. And most importantly, it should be simple to add rich behavior to the rendered markup. In other words, the engine must make it simple to instantiate components that attach to the markup it created.

Page 18: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

Will the template include any code? How much?

Problem How can you separate presentation from logic?

Page 19: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

Code in templates is somewhat frowned upon because it defeats the purpose of templates as a place to isolate the presentation. Certainly, more complex calculations are best performed in plain JavaScript or on the server-side, but there are occasions when template code can be useful. Examples include:

Page 20: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

Loops: A collection is passed in to the template. The template outputs the entire collection by looping over the collection. It's much better for the template to perform the looping, rather than the calling JavaScript, because there is usually some HTML before and after the loop. If the JavaScript was to output that HTML, there would be too much coupling between the JavaScript and the template.

Conditionals: if-then conditions and switch statements are sometimes better performed by the template too. However, if the body of each branch is long, you might prefer to include a different template for each.

Page 21: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

Browser-Side XSLT In many cases, the browser receives an XML response. Where the browser is converting XML to HTML, Browser-Side XSLT is a very direct alternative to this Browser-Side Templating. Templating simplifies presentation, but still requires parsing of the XML, which can be cumbersome. XSLT simplifies the parsing as well, being designed specifically for the purpose of transforming XML.

Browser-Side JSONT Analogous to XML/XSLT transformation, JSONT, a Json Frameworks, transforms data in JavaScript Object Notation (JSON) into HTML using a set of rules. The rules themselves are written in JSON.

Page 22: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

The Problem of Embedded Code in Templates

The "Weight" That You Place on the Client-Side

Visual Metaphor Think of a physical template - a document with most content already present, with a few blanks to populate with current values.How to choose a client template engine?

Page 23: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

Templates are a data rendering method that server-side developers have enjoyed since the old days of classic ASP and PHP. The idea was quite simple (add code blocks and dynamic expressions directly into HTML markup) but it revolutionized web development, which before that relied on the opposite method (spitting HTML from CGI code).

On the client-side, the browser provides two ways to generate HTML: innerHTML and the DOM API. Template rendering is of course possible, but only using a JavaScript library.

Page 24: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating

I’ll try to go over a few things that you might want to check on a template engine. You will want to cherry-pick what’s important to you and what’s not so that you can pick the tool that’s best adapted to your problem.1. Expression delimiter2. Expression language3. Protection against injection attacks4. Template location5. Hooking up events and instantiating components6. Live bindings7. Ease of data field access8. Readability9. Performance10.XHTML compliance11.Nested templates

Page 25: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating2. Expression language

In the simplest cases, you’ll want to inject a simple data field into the template, like {{ Price }}. But many times, you’ll want to go beyond those simple cases and embed a more complex expression into the markup. For example, you might want to display that price with two decimal places, like $42.00. In order to handle that case and more complex ones, it is necessary to have a full expression language.

In the same way, if the template engine allows for code blocks to introduce control structures such as conditional execution or loops, it needs a full programming language.

Some template engines, such as Django, introduce their own new language. Others, such as this, just use what’s already available and familiar: JavaScript. In addition to being familiar, it eliminates the need to write a parser and interpreter, which reduces library code size and gives better performance.

Page 26: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating3. Protection against injection attacks

The frightening thing about almost any single one of the client template engines out there is that they have no mechanism in place to protect against injection attacks, which puts the responsibility to encode and check contents in the hands of the application developer. That’s you.

Most of the engines out there are using a very simple algorithm to build HTML: array joining, and then injecting the result using innerHTML. This is very similar to building SQL by concatenating strings: in a nutshell, you shouldn’t do that. In the same way that SQL is better built using parameterized queries, HTML is more securely built using the DOM API which just eliminates the need for encoding.

Page 27: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating3. Protection against injection attacks

Even when using encoding or the DOM API, there is a number of attributes that still present a fair amount of danger if user data gets injected in them. For example, if you bind the href attribute of a link to a piece of user data, no amount of encoding will protect the application against a user injecting “javascript:doSomeEvil();”.

One thing to understand is that the dangerous contents here is the data, not the template itself, which is trusted as application code is.

Page 28: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating4. Template location

Depending on the library, the template can be embedded in comments, in script tags or just be part of the DOM. It can also be included from a separate file.

Putting the template in comments or script tags easily hides its markup from initial rendering, but it makes it harder to design with existing tools and puts it out of the reach of markup validation tools.

Including from a separate file adds one more request to the server, which might be a problem or not: it might also improve performance by allowing partial caching. The best is to have a choice here, so I’d reject an engine where external files is the only possibility, knowing that all other engines allow external files with minimal effort by feeding a simple XHR’s result into the system.

Page 29: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating4. Template location

Instead of using script tags or comments, ASP.NET AJAX choses to embed the template as real HTML contents anywhere in the document and just hide it from initial rendering using CSS. This makes the code designable using any existing tool, and enables us to use the browser’s native HTML parser to understand the structure of the markup.

Page 30: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating5. Hooking up events and instantiating components

In a modern Web application, you won’t just create plain HTML, you’ll want to hook up events and instantiate components. The template engine might let you do this inline, which is obtrusive but convenient, or it might require you to enrich the DOM after template instantiation through code, or it might give you a choice between the two.

Page 31: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating6. Live bindings

One big advantage of client rendering is that the data remains under raw data form until it reaches the template engine. That means that you have a representation of the data on the client. This in turn means there is an opportunity to monitor changes to the data and to bind UI directly to it, eliminating round-trips to the server along the way.

This is made possible by the fact that templates are compiled by the Ajax framework into a JavaScript function and these bindings get embedded right into that generated function. Because of that, the binding gets evaluated only once, when the template is instantiated.

Page 32: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating7. Ease of data field access

This one is quite simple. Some template engines force you to access the current data item’s field through some special syntax such as “$T.price”. In this engine and several others, you just write “price”.

Page 33: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating8. Readability

This one is quite subjective, but when choosing a template engine, just look at a few samples. Does the code hurt your eyes? Can you understand it right away?

Page 34: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating9. Performance

A template engine must be able to render a reasonable number of data items with a reasonably complex template under the perception threshold. What’s “reasonable” pretty much depends on your application design, but I’d say a hundred items in a typical grid layout should be hardly noticeable. So before you choose, do a mock-up of your design and data and try it. Increase the number of items and see where rendering starts to get noticeable. Usually rendering performance is not linear so this should give you a good idea of how far you can go with each engine. Better to determine that before you invest heavily in one engine.

Page 35: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating10. XHTML compliance

As I said above, this is one you might not care about. Don’t leave yet, it actually goes both ways, as an engine, by enforcing XHTML compliance, might potentially get in the way of writing HTML the way you want.

The lowest level of compliance is that the rendered output is compliant. Being template engines, most if not all engines enable you to create compliant or horribly broken markup, depending on your own style. What it must absolutely not do is prevent you from generating compliant markup.

The second level of compliance is that the template code itself, before data is injected, is compliant. This is much less common. Even less common is that the compliance requirement does not impose too strong a constraint on the markup you have to write.

In other words, a good template engine lets you write XHTML but doesn’t force you to.

Page 36: Browser Side Templating With Asp.Net 4.0 Ajax

Browser Side Templating11. Nested templates

Rendering a template within a template might look like a whacky scenario at first if the engine understands control structures such as loops. In reality, if you include something like live bindings into the mix, you will want for example an inner template to be re-drawn when the outer data item changes. This will be much easier to achieve with nested templates.

So if this is a scenario that you care about, make sure that your engine handles that case gracefully.

Page 37: Browser Side Templating With Asp.Net 4.0 Ajax

Key Features ASP.NET AJAX 4.0

ADO.NET Data Services support

WCF and ASMX Web service integration

ASP.NET AJAX Client Templates

Declarative instantiation of client-side controls and behaviors

Observable pattern for plain JavaScript objects

Live Bindings

Markup Extensions e.g. {formatCurrency "US", value={{number}}}

Page 38: Browser Side Templating With Asp.Net 4.0 Ajax

DataView control and DataContext component

Command Bubbling

Change tracking and identity management

Extension methods allowing change tracking and read-write client-server scenarios using other JSON services, including RESTful or JSONP based services

Key Features ASP.NET AJAX 4.0

Page 39: Browser Side Templating With Asp.Net 4.0 Ajax

Live Binding

What is Live Binding?

Live binding is having the data bound in real-time. Meaning when there's any change in the data source, the changes are reflected to the data bound interface instantly and vice versa. For example if you have an interface component, like a table, bound to a data source, like an array, any change to that array from the code is reflected in the view table instantly. If you are using an edit template for updating the data of a selected row of the table, the data in the table will get updated as you change a field in your edit form if both the table and the form use "Live Binding". Pretty cool, right?

Page 40: Browser Side Templating With Asp.Net 4.0 Ajax

Live Binding

Inside Live Binding This is all done through client-side script, JavaScript. But how does it come in action? The core of the live binding is the implementation of an "Observer" pattern. The observer pattern enables an object to be notified about changes that occur in another object. This is not an event handler based pattern which we often misuse as an observer pattern. ASP.NET AJAX 4.0 implements this pattern completely. It adds observer functionality to ordinary JavaScript objects or arrays so that they raise change notifications when they are modified through the Sys.Observer interface.

Page 41: Browser Side Templating With Asp.Net 4.0 Ajax

Live Bindingvar product = { name: "Foo Choclate Bar", price: 1, inStock: true }

var productsPublisher = Sys.Observer.observe(product); //The publisher which is being observed

Sys.Observer.addPropertyChanged(productsPublisher, productSubscriber); //Add a subscriber for any property change on the publisher

productsPublisher.setValue("inStock", false); //Change a property

function productSubscriber(product, eventArgs) //Subscriber {    if (eventArgs.get_propertyName() == "inStock" && product.inStock == false) {        alert("The product is out of stock");    }}

Page 42: Browser Side Templating With Asp.Net 4.0 Ajax

Live Binding

The key components used for the Live Binding are Templates, the DataView control and the DataContext class. The AdoNetDataContext class is also there for additional ADO.NET support.

Page 43: Browser Side Templating With Asp.Net 4.0 Ajax

ASP.NET AJAX Templates and Data Binding

DEMO

Page 44: Browser Side Templating With Asp.Net 4.0 Ajax

New Client Components

DataView control renders dataUses a Client TemplateRepeater if Data is an ArrayDetails View if Data is an ObjectFetching Data from a Data Provider

DataSource component integrates data sources

.asmxWCFADO.NET Data Servicesetc.

http://ajax.asp.nethttp://codeplex.com/ aspnet

Page 45: Browser Side Templating With Asp.Net 4.0 Ajax

DataView controlData can be provided to a DataView control for live binding in a number of ways.

1. Setting the data property of the control decoratively: A declarative binding can be done through assigning a value to the data property as follows:<ul sys:attach="dataview" class="sys-template" dataview:data="{{ employeeList }}">       <li>             <h3>{{ Name }}</h3>            <div>{{ Address }}</div>      </li>  </ul>

Page 46: Browser Side Templating With Asp.Net 4.0 Ajax

DataView control2. Setting the data property of the control through code: This approach can be implemented as follows:<script type="text/javascript">      function pageLoad() {        employeeService.GetEmployeeList(querySuccess);     }     function querySuccess(result) {        $find("employeeList").set_data(result);     }  </script>  <ul id="employeeList" sys:attach="dataview" class="float master sys-template">     <li>         <h3>{{ Name }}</h3>        <div>{{  parseFloat(salary).localeFormat("C") }}</div>     </li>  </ul>  

Page 47: Browser Side Templating With Asp.Net 4.0 Ajax

DataView control3. Using WCF or ASP.NET web service as dataProvider: A WCF or ASP.NET web service can be specified in the dataProvider property of the control.<ul sys:attach="dataview" class="sys-template"       dataview:autofetch="true"      dataview:dataprovider=employeeService.svc"      dataview:fetchoperation="GetEmployeeList">     <li>         <h3>{{ Name }}</h3>        <div>{{ Address }}</div>        </li>  </ul> 

Page 48: Browser Side Templating With Asp.Net 4.0 Ajax

DataView control4. Using DataContext classes as dataProvider: The DataContext class can be used as follows:<script type="text/javascript">       var dataContext = new Sys.Data.DataContext();      dataContext.set_serviceUri("emplyeeService.svc");      dataContext.initialize();  </script>  <ul sys:attach="dataview" class="sys-template "      dataview:autofetch="true"      dataview:dataprovider="{{ dataContext }}"      dataview:fetchoperation="GetEmployeeList">      <li>           <h3>{binding Name}</h3>          <div>{binding Address}</div>      </li>  </ul>

Page 49: Browser Side Templating With Asp.Net 4.0 Ajax

Data BindingOne-way, One-time - The data value is updated only the first time that data binding is invoked. {{ CompanyName }}

One-way, Live - If the underlying data item is modified, the rendered data value is updated automatically.<span>{binding CompanyName}</span>

Two-way, Live - If the user changes the data value, the value of the underlying data item is updated. In addition, if the data item is modified from another source, the rendered data value is updated.<input type=“text” value=“{binding CompanyName}” />

Page 50: Browser Side Templating With Asp.Net 4.0 Ajax

Data BindingAdditional Features

The syntax also provides functions for converting data values to rendered values, or converting back from values entered in UI to an appropriately formatted data value. The following example shows how to provide conversion functions:

<input type="text" value="{binding Distance, convert=toMiles,          convertBack=fromMiles}"/>  

This similar syntax can be used to specify binding mode as well.

<input type="text" value="{binding Distance, mode=oneWay}"/>

The default binding behavior for text-boxes and other input controls is two-way and for all other controls is one-way.

Page 51: Browser Side Templating With Asp.Net 4.0 Ajax

Rude Objections{impediments to a perfect future}

Browser Back/Forward buttonAccessibilitySearch Engine Optimization (SEO)JavaScript disabled (Mobile Devices)

Page 52: Browser Side Templating With Asp.Net 4.0 Ajax

Technology Independent

Client-Side ASP.NET AJAX…

Works with any modern browser including IE, Firefox, Chrome, Safari, and Opera.

Works with any back-end technology that exposes JSON (not dependent on ASP.NET)

Works with HTML pages, no need for ASP.NET.

Page 53: Browser Side Templating With Asp.Net 4.0 Ajax

Thank YouFor patiently listening