First, take a look at this, and think about how you would implement this sort of UI in ASP.NET. It’s a live demo, so have a play – you can add, remove and rename folders.
In standard, server-centric ASP.NET, this would be incredibly painful to create. You’d be fussing over viewstate, naming containers, event bubbling, and every button-press from the end user would result in a long, tedious postback. Even just maintaining the tree expansion state between postbacks would be awkward.
For simplicity, we’re using
XML to represent our data model
(view this by clicking “Show model XML” in the demo)
- XSLT to build the HTML view of the model
The basic mechanics of this UI technique are thus:
When the user finally submits the form to the server (e.g. postback in ASP.NET), the TEXTAREA contains the updated XML data model, which is easily parsed, validated and processed by the server.
For this to work, your browser has to be able to
- Parse an XML string into an XML document (and serialize it back)
- Transform an XML document using XSLT
All modern browsers can do the above natively, but if you need to support one that doesn’t – but it does support AJAX (XMLHttpRequest) – you can do the parsing/transforming on the server.
In the example, I wrote code that natively supports IE and Firefox, but when I’ve used this technique in production, I used the excellent Sarissa library to handle all the cross-platform business and give me wider browser support.
- You can build increasingly sophisticated UIs without building increasingly sophisticated code to support it.
- XML/XSLT handle repeating/recursive UIs so very naturally
- It’s dead easy to mix this approach with standard ASP.NET web controls, because the MVC controls naturally retain their state between postbacks.
- It’s like instant AJAX. In other words, the end user experience is one where the UI updates immediately without postbacks, but it’s even better because there are no asynchronous HTTP requests to wait for. Of course you can’t do everything you could with classic AJAX.
- Though this technique is great for highly dynamic UIs (especially repeating/recursive ones), it’s overkill for simple forms
- You can’t embed ASP.NET server-side controls inside the MVC controls (but you can use them elsewhere on the same page).
If there’s one thing I really don’t like here it’s XSLT. Oh yes it’s very clever, but it’s ridiculously verbose and virtually impossible to read quickly. And it lacks extensibility. It just looks ugly! If anyone’s interested, I may follow this up with a tutorial on building simpler, faster and more powerful MVC UIs using the fabulous JSON.