Strongly typed models on your layout

One of the early issues I disliked when moving to .net’s MVC was the lack of strongly typed objects available in layout pages. A lot of times I’ll want to display failry static, session(ish) type information in a many places “around” the main content area.

Information like the current users name, email and even other not so generic information like permissions (we rolled our own permissions architecture) or current context (our website has many “portals”) all seemed like fair game. I also noticed many times we’ll need this information in the main content view or even on a partial/ajax request.

A couple solutions came to mind.

I initially created many partial actions which retrieved the specific information I needed for the particular area but soon found that to be too cumbersome. Even if all the information I needed was cached in nHibernate for the entire request, why must I go a round about way to get it each time.

Another solution was to stick what I needed in the context object, or even the ‘He-Who-Must-Not-Be-Named’ – señor ViewBag. Again though leading back to my original thesis – I wanted this to be typed safe – so I finally settled on this quick and simple solution.

First I created a simple view model, added any dependencies and populated it with the info I’d want available to my layouts and views.

public class BaseViewModel
   private readonly IContextRepository _contextRepository;

   public BaseViewModel(IContextRepository contextRepository)
      _contextRepository = contextRepository;
      SelectedContext = _contextRepository.GetCurrent();
   // assume for the sake of the example a ContextViewModel is just a simple dto with an Id and Name representing a context business object
   public ContextViewModel SelectedContext { get; private set;  }

Then in my base controller, during the OnActionExecuting I create the BaseViewModel using my resolver. It’s important to note that the BaseViewModel (and all of it’s properties) gets created between the unitOfWork transaction to ensure I’m not accessing the database at the view level. If there’s questions about why it’s important, I’ll make another blog post soon to respond.

public class BaseController : Controller
  protected BaseViewModel ModelBase { get; private set; }

  private readonly IMapService _mapService = Resolver.Get<IMapService>();
  private IUnitOfWork _unitOfWork;

  protected override void OnResultExecuting(ResultExecutingContext filterContext)
    var contextItems = filterContext.HttpContext.Items;
    if (contextItems["ModelBase"] == null)
      contextItems["ModelBase"] = ModelBase;

  protected override void OnActionExecuting(ActionExecutingContext filterContext)
    _unitOfWork = Resolver.Get<IUnitOfWork>();
    ModelBase = new BaseViewModel(Resolver.Get<IContextRepository>());

After creating it, I simply place it in the contextItems dictionary to be used by the views – simple as that. This allows type safe, transaction safe references to information in the layouts, and really all over the place.


<div>Hey there you're in the @ModelBase.SelectedContext.Name section of our site!</div>

The naming is especially nice since intellisense will pick up the BaseViewModel when the developer types “Model” as he’ll see “ModelBase” in the drop down and hopefully remember to use it. It’s also made refactoring quite a bit easier as we now have one place to make modifications to retrieving that commonly used information.

(Now of course with great power…)
Make sure you only put in to this baseViewModel what you’ll be accessing quite often (nearly if not every request) otherwise obviously you won’t get as much out of it as you could. It’s also recommended, like always, if you are working with a view model of any kind, keep it to primitives or dtos of primitives mapped via nHibernate or AutoMapper.

Please don’t expose your entire user/company/kitchenSink object using this method as I’ll plead the 5th. =P


Simple Example of MVC3 with Spine

Github: MVC3 with Spine

It’s much harder keeping up with a blog than I originally thought (so many half written posts) but I just wanted to share with you a couple examples of interesting interactions between Server and Client MVC.

One of the pages we had recently worked on had a complex workflow for creating/updating user generated lists of ints, strings or datetime objects based on some business case. The lists required a little computation and a lot of user hand-holding so I opted for a single page, client side solution using a coffeescript MVC library (Spinejs) and client side templating via plain old jQuery tmpl (now depreciated) with minimal server interaction.

This something a lot of Ruby, Python and PHP developers have been doing for years but is fairly new to the .net community (me at least). I mean why must the server need to know about each item in the list as it’s created? Why not push ‘state’ up the stack and let the client be the source of truth (perform crud actions) while this page is active.


On the client side I ended up with very standard, out of the box, spine code to create and save the list items.


class FooModel extends Spine.Model
  @configure 'Foo', 'value'

  constructor: () ->

Rendering was a little more complex being as though I had to perform a small amount of computation, messaging and recalculating the current list based on prior inputs but once that was out of the way I could use my client side templates to render.

Client template in html..

<script id="foo-item-template" type="text/x-jquery-tmpl">
    <div class="foo-item" data-id="${id}">
      <input type="text" value="${value}"/>
      <input type="button" name="delete" value="delete" />

Spine’s controller class handles the events and re-renders based on the current list of foo models using the template declared in the constructor.


class FooController extends Spine.Controller
    'click :button[name="add"]' : 'addFoo'
    'click :button[name="delete"]' : 'deleteFoo'
    'click :button[name="save"]' : 'saveFoo'
    'change :input' : 'updateFoo'

  constructor: () ->
    $("#foo-item-template").template "fooTemplate"
#...other code to do all of the things!

  renderTemplate: ->
    sortedList = FooModel.all().sort FooCompare
    $('#foo-list').append $.tmpl("fooTemplate", sortedList)

The code I posted above is of course scaled down, removing all of the other events (saving, creating, deleting, etc) and calculations but you get the idea.


A list can be one of three types (string, int, datetime) so they all require different messaging. I didn’t want to have 3 client templates sitting on my page with coffeecript sorting through values, picking a different template to render for each type so instead I used the magic of server partials.

By creating different partials on the server which house the different client side templates (and possibly their respective logic), we allow the server to still be in charge of how it’s rendered. While not terribly elegant it does get the job done for this example and you can imagine the possibilities with more complex systems.


@model Areas.Foo.Models.CreaetOrUpdateViewModel

<div id="foo-wrapper">
    <input value="add" name="add" type="button"/>
    <input value="save" name="save" type="button"/>
    <div id="foo-list"></div>


The partial now holds the html client template for the specific type.


<script id="foo-item-template" type="text/x-jquery-tmpl">
    <div class="foo-item" data-id="${id}">
      <input type="text" value="${value}"/>
      <input type="button" name="delete" value="delete" />

  function FooCompare(x, y) {
        return parseFloat(x.value.replace( /,/g , ''), 10) - parseFloat(y.value.replace( /,/g , ''), 10);

The end result is

  1. a controller who only deals in complete state gets and saves
  2. javascript that performs a single task, agnostic of the type/templates it’s dealing with
  3. a simple view that allows the model to decide which client side template it will need

Really enjoying it so far, I’ll share more thoughts as I go.

Here is the github for the example project.

Things to note

Coffeescript has really shined on my current project. It’s ease of use, quick ramp up time and simple class/inheritance model makes it so that any of my developers can jump in and make an important bug fix in a relatively short amount of time.

Though I’ve ben very impressed with Spinejs, there are a few things I’d like to point out. Models are actually more like repositories which create a json objects representing your ‘model‘. It can feel awkward at first to use the same ‘class‘ (I know it’s not really a class) to talk about the repo and actual object but it functions well enough.

I’ve really enjoyed Spinejs’ events though. Having multiple controllers on one page interacting by firing events is written cleanly and simply, or at least as simply as javascript will allow it.

I wouldn’t recommend jQuery tmpl for rendering more than 200 complex templates at a time. We have a page currently which does exactly that but with a little imagination (magic, fun with javascript…) we were able to break up rendering asynchronously and re-render more intelligently. So far though it’s been very easy and a pleasure to work with.

-Jason Hooten

Namespaces in CoffeeScript

It’s probably my .net background but I love structured namespaces.As such I get a sick feeling in my stomach when adding a Javacript method to global or window. It feels dirty like going to the Austin .Net User Group and grabbing 5 slices of pizza instead of 3. (hey there was a ton left over on Monday!)

Ever since I discovered the elegance that is Coffeescript, with it’s multitude of cool stuff like classes, splats, and ruby syntax, I’ve often wondered why no consideration was taken in implementing nice, easy and clean namespaces.

By default CoffeeScript makes every function, class and member inside a file locally scoped to that file. If you need to expose something to you can either attach it to the window object or exports object in CommonJS. = 'bar'
window.pair = class
  constructor: (@key, @value) ->

This is all well and great but sometimes (especially when you’re writing your own Core library for an enterprise level web app) you run into collisions with other not so well written libraries – you pull your hair out and eat more pizza.

Debugging and refactoring these types of issues can be a monumental pain, so in an effort to get out ahead of the the problem I set out to find namespacing in Javascript so I could then write it in CoffeeScript.

The first place I looked like any good little developer was Stack Overflow. After two or three hours of derailed fun (so that’s how to use nServiceBus!) I finally came across a link to a blog post by Angus Croll – which also happens to be the first result when you google ‘namespacing in javascript’! Efficiency 4tw!

The idea is you create global variable (in jQuery it’s ‘$’ for example) and run it through an anonymous method which binds your methods to it, much like a ‘class’ prototype.

var myApp = {};
	(function(context) {
	    var id = 0; = function() {
	        return id++;

	    context.reset = function() {
	        id = 0;

In case you’re new to Javascript, the (myApp) at the bottom of the method just means to run it automagically when it’s loaded, with ‘myApp’ as the parameter.
Taking this idea and running with it I came up with a pseudo namespace of my own in CoffeeScript.


namespace = (name) ->
  window[name] = window[name] or {}

namespace 'myNameSpace'

myNameSpace.pair = class
  constructor: (@key, @value) ->

Interpreted Javascript–

(function() {
  var namespace;
  namespace = function(name) {
    return window[name] = window[name] || {};
  myNameSpace.pair = (function() {
    function _Class(key, value) {
      this.key = key;
      this.value = value;
    return _Class;

For each new namespace just add “namespace ‘{your_namespace}'” and start using it like where I used it on the ‘pair’ class. Now you can namespace to your hearts content!

So to bring this back into the .net MVC sphere…

How I have {our project} set up is there is an {our project} with a lot of boiler plate client code like toast, browser caching and tooltips. Then each Area also has an {our project}.{our area}.coffee file which is namespaced to that area. Later when I integrate Spinejs and Knockoutjs, this will make refactoring server code which is heavily dependent on client code ‘much easier‘.