MVVM and .NET: A Great Combo for Web Application Development
Using the MVVM pattern and available tools, you can build responsive web apps quickly
October 1, 2013
You work with a small software development team. When you started the project you're currently working on, an ASP.NET-based web application, eight months sounded like enough time for delivery. Your team decided to use ASP.NET MVC because everyone was comfortable developing in the .NET Framework. After seven months and a lot of jQuery, your team is not even close to delivering a quality code base. Furthermore, even if you could deliver all the features on time, your code has more than a few trouble spots that you would have liked to refactor, and code maintenance will be a challenge.
Does this scenario sound familiar? I had a similar experience on a project, which was my first and last project in ASP.NET MVC because I knew there had to be a better way to develop web applications. In my experience, the Model-View-ViewModel (MVVM) pattern provides that better way and is preferable to Model-View-Controller (MVC) pattern on which ASP.NET MVC is based. I have found that MVVM is easier to understand and implement than MVC and facilitates the development of simpler, more reusable code. Here I will provide an introduction to MVVM, first comparing the MVC and MVVM architectures and then giving an overview of some popular available frameworks that support an MVVM-based approach to web application development.
Architecture Is Important
In theory, the MVC pattern is a good idea. Views are responsible for displaying the data, controllers execute your business logic and manage the views, and models hide the complexities of dealing with a database. However, in practice, working with MVC can be problematic. Controllers will spawn many views, violating the single-responsibility principle, and your business logic will creep into all layers of your application, as Figure 1 illustrates. ASP.NET MVC makes it especially easy to make such mistakes, resulting in fundamentally flawed application architectures.
Figure 1: MVC Implementation
Writing C# code in your views also has performance and scalability implications. All data and HTML that you want to be displayed in the browser are compiled on the server. Rendering views on the server requires more resources, reducing the number of users that can be served concurrently on the server. The amount of data transferred to the client during application execution is inadvertently increased, which impacts bandwidth needs because with every request brand-new HTML could be generated, making caching strategies difficult to implement.
Silverlight Had the Right Idea
Silverlight—and more importantly, XAML—has been an interesting technology since its introduction. From a web development perspective, XAML encapsulated HTML5 and Cascading Style Sheets level 3 (CSS3) functionalities before any browser supported them. Data binding in Silverlight presents a clear break from event-based UI programming, and in Silverlight 5 with Async CTP, you get a break from callback-based asynchronous programming.
All these technologies allow for an effective MVVM implementation. ViewModels neatly encapsulate any presentation logic and allow for simpler View code by acting as a specialized version of the model, as shown in Figure 2. The relationship between a View and ViewModel is straightforward, allowing for more natural ways to wrap UI behavior in reusable user controls. Silverlight made me a believer in MVVM.
Figure 2: MVVM with a .NET Back End
Under MVVM, the architecture inherently enforces the proper separation of concerns. Business logic is clearly separated from presentation logic. So when a View is developed, it stays developed, because fixing a bug in one View's functionality doesn't impact other views. On the flip side, if you've used visual inheritance effectively and created reusable user controls, fixing a bug in one place can fix issues throughout the application.
In an MVVM application, the client code lives on the client side, resulting a more responsive and rich user experience by default. During application execution, the amount of bandwidth required is reduced to a bare minimum, while enabling the app to gracefully handle semi-connected application states.
My experience with a development project for the National Oceanic and Atmospheric Agency (NOAA) illustrates why I've come to appreciate the MVVM pattern. This MVVM-based project had more than 50 views, and I was the sole application developer. The project was delivered with only minor delays, and about half of the code base was delivered as reusable code. Unlike some other projects I've been a part of, on this project the quality and reliability of the application consistently improved over time. Furthermore, I was able to gracefully address last-minute requirements changes.
The Web Is Ready
Although Silverlight has fallen from prominence, MVVM still exists as a viable pattern for web development. Several excellent frameworks and other options have emerged that add support for key MVVM concepts to HTML and JavaScript. These options, listed below, are a boon for MVVM development. However, to get the most value from any of these options, I advise you to set aside everything you know about web development and consider a brand-new approach.
Knockout.js makes data binding possible. Boilerplate.js provides a very thin configuration-based framework to help you get started building large-scale JavaScript Single Page Applications (SPAs). Another option is John Papa's Hot Towel SPA template. However, this is a convention-based framework and doesn't offer full control over the nitty-gritty details.
Using JavaScript in an enterprise environment is also challenging. Require.js allows modularization of the code base, which is a critical component in managing complex JavaScript applications.
ECMAScript 5's Strict Mode, which you enable in your code via a statement containing the string "use strict", is a handy method for preventing the use of global variables in JavaScript. Additionally, you can use the revealing module pattern to enforce proper encapsulation.
As a fan of C# and Anders Hejlsberg, I've investigated TypeScript, and I can see its value in developing a JavaScript library containing complicated business logic. However, I found no place for TypeScript in my architecture because it doesn't integrate well with Require.js and other plug-ins.
The Q library lets you create sophisticated multi-threaded JavaScript applications using async promises.
I still haven't addressed the elephant in the room. How will any of these technologies work with a Microsoft platform-based back end that you understand? We'll consider that question next.
Microsoft Is Ready, Too
At the Microsoft Build 2013 conference, I was pleasantly surprised to discover how much Microsoft has changed its stance on supporting standards-based web technologies. At last in Visual Studio 2013, Microsoft has provided a world-class HTML editor offering an amazing HTML5 code-development experience. I highly recommend that you set up Mads Kristensen's recently open-sourced Web Essentials plug-in and try coding some CSS with it.
Here are some additional tools that support back-end coding for an application using MVVM architecture.
Web API 2 lets you easily write RESTful services and enable your apps to consume them. Web API 2 is straightforward to secure and also to debug.
Entity Framework 6 lets you write a fully async back-end stack, which greatly improves the scalability of your solution.
It is possible to tie your back end to your front end in a painless and rapid manner. The Breeze.js project works with the Entity Framework, Web API, and OData technologies to automatically manage data-retrieval and syncing chores. This technology is quite similar to WCF RIA Services; however, it is not a black box but rather an open source project. You can query the data you need from your JavaScript client, which allows for maximum flexibility during development.
Breeze effortlessly injects itself into the MVVM architecture, and if correctly abstracted, it is a technology that you don't need to be married to indefinitely. The data service layer on the client properly protects your front-end code from being specific to any back-end technology. Similarly, RESTful Web APIs can work with any front-end technology. However, it is still important to keep all business logic in the repository/service layer.
Get Started Today
An MVVM-based application architecture can be lean enough to enable you to build a web application quickly, while also flexible enough to scale and incorporate security features when those needs arise. I've presented some of the technologies I've found useful in creating MVVM application architectures. An additional tool that you might find useful is the ExcellaLean project, a boilerplate lean enterprise architecture that incorporates the previously discussed technologies and patterns and can help you jump-start your next web development project.
Read more about:
MicrosoftAbout the Author
You May Also Like