Grouping by feature in ASP.Net MVC


When I initially switched from using ASP.Net Web Forms to MVC as my standard technology for building web sites on the Microsoft stack I really liked the clean separation of the models, views and controllers. No more messy code-behind files with scattered business logic all over the place!

After a while though, I started to get kind of frustrated when editing the different parts of the code. I often find that a change in one type of file (e.g. the model) tend to result in corresponding changes in other related files (the view or the controller) and for any reasonably large project you’ll start to spend considerable time in the Solution Explorer trying to find the files that are affected by your modifications. It turns out that the default project structure of ASP.Net MVC actually does a pretty poor job of limiting change propagation between the files used by a certain feature. It’s still much better than Web Forms, but it’s by no means perfect.

The problem is that the default project structure separates the files by file type first and then by controller. This image shows the default project structure for ASP.Net MVC:

Default ASP.Net MVC project structure

Default ASP.Net MVC project structure

The interesting folders are Controllers, Models (which really should be called ViewModels) and Views. A given feature, for example the Index action on the Account controller, is implemented using files in all these folders and potentially also one or more files in the Scripts folder, if Javascript is used (which is very likely these days). Even if you need to make only a simple change, such as adding a property to the model and show it in a view, you’ll probably need to edit files in several of these directories which is fiddly since they are completely separated in the folder structure.

Wouldn’t it be much better to group files by feature instead? Yes, of course it would, when you think about it. Fortunately it’s quite easy to reconfigure ASP.Net MVC a bit to accomplish this. This is the goal:

Grouping by feature

Grouping by feature


Instead of the Controllers, Models and Views folders, we now have a Features folder. Each controller now has a separate sub-folder and each action method has a sub-folder of their own:

  • Features/
    • Controller1/
      • Action 1/
      • Action 2/
    • Controller2/
      • Action 1/
      • Action 2/

Each action folder contains the files needed for its implementation, such as the view, view model and specific Javascript files. The controller is stored on level up, in the controller folder.

What we accomplish by doing this is the following:

  1. All the files that are likely to be affected by a modification are stored together and are therefore much easier to find.
  2. It’s also easier to get an overview of the implementation of a feature and this in turn makes it easier to understand and work with the code base.
  3. It’s much easier to delete a feature and all related files. All that has to be done is to delete the action folder for the feature, and the corresponding controller action.


After that rather long motivation, I’ll now show how to implement the group by feature structure. Luckily, it’s not very hard once you know the trick. This is what has to be done:

  1. Create a new folder called Features, and sub-folders for the controllers.
  2. Move the controller classes into their respective sub-folders. They don’t need to be changed in any way for this to work (although it might be nice to adjust their namespaces to reflect their new locations). It turns out that MVC does not assume that the controllers are located in any specific folder, they can be placed anywhere we like.
  3. Create sub-folders for each controller action and move their view files there. Rename the view files to View.html as there’s no need to reflect the action name in the file name anymore.

If you try to run your application at this point, you’ll get an error saying that the view cannot be found:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

This is exactly what we’d expect, as we just moved the files.

What we need to do is to tell MVC to look for the view files in their new locations and this can be accomplished by creating a custom view engine. That sounds much harder than it is, since we can simply inherit the standard Razor view engine and override its folder setup:

using System.Web.Mvc;

namespace RetailHouse.ePos.Web.Utils
    /// <summary>
    /// Modified from the suggestion at
    /// </summary>
    public class FeatureViewLocationRazorViewEngine : RazorViewEngine
        public FeatureViewLocationRazorViewEngine()
            var featureFolderViewLocationFormats = new[]
                // First: Look in the feature folder
                // If needed: standard  locations

            ViewLocationFormats = featureFolderViewLocationFormats;
            MasterLocationFormats = featureFolderViewLocationFormats;
            PartialViewLocationFormats = featureFolderViewLocationFormats;

The above creates a view engine that searches the following folders in order (assuming the Url is /Foo/Index):

  1. ~/Features/Foo/Index/View.cshtml
  2. ~/Features/Foo/Shared/Index.cshtml
  3. ~/Features/Shared/Index/View.cshtml
  4. ~/Views/Foo/Index.cshtml
  5. ~/Views/Shared/Index.cshtml

The last two are just used for backward compatibility so that it isn’t necessary to refactor all controllers at once.

To use the new view engine, do the following on application startup:

ViewEngines.Engines.Add(new FeatureViewLocationRazorViewEngine());

The view will now load and the application will work as before, but with better structure.

The last step is to move view models and custom Javascript files into the action folders as well (note that the latter requires adjusting the paths in the HTML code that includes the Javascript files to reflect the new locations).

Once everything is up and running, the project becomes much easier to work with and when you get used to working like this you really start to wonder why Microsoft is not doing it by default in their Visual Studio templates. Maybe in a future version?


2014-11-21 Updated the images to clarify the concept

Overriding the placement of validation error messages in knockout-validation

By default, knockout-validation places error messages just after the input element containing the error. This may not be what you want, and you can create UI elements of your own and bind them to validation error messages but this means writing a lot of boilerplate markup and it messes up the HTML. An alternative to this is to override the knockout-validation function that creates the error messages on the page. For example:

ko.validation.insertValidationMessage = function(element) {
    var span = document.createElement('SPAN');
    span.className = "myErrorClass";

    if ($(element).hasClass("error-before"))
        element.parentNode.insertBefore(span, element);
        element.parentNode.insertBefore(span, element.nextSibling);

    return span;

In this example I check whether the input element contains the custom class “error-before”, and if so, I move the error message to before rather than after the input field.

Another example, suitable for Bootstrap when using input groups:

ko.validation.insertValidationMessage = function(element) {
    var span = document.createElement('SPAN');
    span.className = "myErrorClass";

    var inputGroups = $(element).closest(".input-group");
    if (inputGroups.length > 0) {
        // We're in an input-group so we place the message after
        // the group rather than inside it in order to not break the design
    } else {
        // The default in knockout-validation
        element.parentNode.insertBefore(span, element.nextSibling);
    return span;

One disadvantage of this is that we have no access to the knockout-validation options such as “errorMessageClass” so we have to hard code that value here (“myErrorClass” in the examples above.


HTML 5 canvas performance experiment

I have started playing around with HTML 5 canvas to see what it can be used for and decided to test the performance with an old animated plasma-like demo effect that I used to do in my early days of programming some 20 years ago (I can’t believe I’m that old, how did that happen?).

Here’s a screen dump of the effect on a 600 by 400 pixel canvas:

Screen dump of the plasma effect in action

Here’s the page with the demo in real-life:

In Chrome I get a frame rate of about 18 frames per second on my Intel Core i7 2.70 GHz laptop with Mobile Intel graphics circuits. That’s okay I suppose, since most of the time is spent in the calculations of the color values using the following formula:

var r = Math.cos(animationOfffset + x/100 * y /100) * 255;
var g = Math.sin(animationOfffset + ((x * x) / 300) * (y / 300)) * 255;
var b = Math.cos(animationOfffset + (x-y) / 500) * 255;

This calculation has to be done for each of the (600 x 400 = 240 000) pixels in each frame. The limiting performance factor in this demo is definetely the CPU rather than the graphical performance of the canvas.

However, when I tried the demo in IE 9 on the same machine, I got about 5 fps! That’s 4 times slower! I have also tried the same demo with IE 10 and while that’s faster than IE 9, it’s still about 2.5 times slower than Chrome on the same machine.

All is not bad for IE though since it rendered the rotating text better. Comparing IE and Chrome side by side it’s obvious that IE has more stable text rendering, in Chrome the individual characters jiggle slightly when rotating the text. Once you notice it, it’s actually rather ugly.

I also tested the demo on my Samsung Galaxy S3 mobile and got 4 fps in Chrome and about the same in the built-in browser. About the same figures as for IE on my laptop. Not bad for a mobile phone…

To conclude, it’s apparently still very important to take the different browsers you’re running you’re Javascript and HTML 5 code on into account when developing web applications. It’s the 90s all over again… 😉

PS. If you try the demo yourself, feel free to post your frame rates in a comment to this post, It’ll be interesting to see how much it differs.

UPDATE 2012-12-06:

I have now tried replacing the calls to the Math.sin and Math.cos functions with pregenerated lookup tables (inspired by this code: Professor Cloud’s Fast Sine demo) and the new demo can be found here:

I now get 42 fps in Chrome on my laptop, i.e. more than doubled performance, which is rather nice. However, the result in IE 9 is still only 5 fps, the same as before. So now Chrome is 8 times faster!

In Chrome on my Samsung Galaxy S3, the result is now 5 fps, also not a great improvement. The only deduction I can make from this is that for IE9 and Galaxy S3, it wasn’t the maths that limited the performance, but something else in the code. I don’t know what it might be so if anyone can shed some light on this it would really appreciated.


Refreshing data in jQuery DataTables

Allan Jardine’s DataTables is a very powerful and slick jQuery plugin for displaying tabular data. It has many features and can do most of what you might want. One thing that’s curiously difficult though, is how to refresh the contents in a simple way, so I for my own reference, and possibly for the benefit of others as well, here’s a complete example of one way if doing this:

<table id="HelpdeskOverview">
function InitOverviewDataTable()
  oOverviewTable =$('#HelpdeskOverview').dataTable(
    "bPaginate": true,
    "bJQueryUI": true,  // ThemeRoller-stöd
    "bLengthChange": false,
    "bFilter": false,
    "bSort": false,
    "bInfo": true,
    "bAutoWidth": true,
    "bProcessing": true,
    "iDisplayLength": 10,
    "sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'

function RefreshTable(tableId, urlData)
  $.getJSON(urlData, null, function( json )
    table = $(tableId).dataTable();
    oSettings = table.fnSettings();

    for (var i=0; i<json.aaData.length; i++)
      table.oApi._fnAddData(oSettings, json.aaData[i]);

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();

function AutoReload()
  RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');
  setTimeout(function(){AutoReload();}, 30000);

$(document).ready(function () {
  setTimeout(function(){AutoReload();}, 30000);

The key is of course the RefreshTable function.