The concept of the ViewModel isn't just for ASP.NET MVC, as you'll see references to ViewModels throughout the web in articles and blog posts about the MVC, MVP, and MVVM patterns. Those posts and articles can center around any number of technologies such as ASP.NET, Silverlight, WPF, or MVC... This post will investigate ViewModels as they apply to the world of ASP.NET MVC.

What is an ASP.NET MVC ViewModel?

In ASP.NET MVC, ViewModels allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendering by the view. The below image illustrates the concept of a ViewModel:

The purpose of a ViewModel is for the view to have a single object to render, alleviating the need for UI logic code in the view that would otherwise be necessary. This means the only responsibility, or concern, of the view is to render that single ViewModel object, aiding in a cleaner separation of concerns (SoC). Concerns are distinct aspects of the application that have a particular purpose (i.e., concern), and keeping these aspects apart means your application is more organized, and the code more focused. Putting data manipulation code in its own location away from the view and controller, enforces SoC.

Using ViewModels in MVC for finer granularity and better SoC leads to more easily maintainable and testable code. Remember, unit testing is about testing small units.

Along with better coding practices, there are many business reasons demonstrating why you might consider using ViewModels:

·         Incorporating dropdown lists of lookup data into a related entity

·         Master-detail records view

·         Pagination: combining actual data and paging information

·         Components like a shopping cart or user profile widget

·         Dashboards, with multiple sources of disparate data

·         Reports, often with aggregate data

The above scenarios are common to a wide variety of applications, and deal with more complex data than basic CRUD forms-over-data page (e.g., a simple 1:1 mapping to the db table). For example, providing a list of states, and ensuring that the state that matches the state of current customer, means that you need to either provide two sets of data or a single set of customer/state data combined, as shown in the image below.

Some scenarios such as a lookup table representing states in the USA, could easily work with either ViewModels or a ViewBag/ViewData object, so there is some potential overlap at times. It's up to the application architects and developers to decide what works best with their exact use case.

Creating a ViewModel

Although a ViewModel consists of multiple entities, at its core a ViewModel is still just a class - and one that doesn't even inherit from anything special, as many MVC classes do. 

Physically, ViewModels can exist in different locations, listed below:

·         In a folder called ViewModels that resides in the root of the project. (small apps)

·         As a .dll referenced from the MVC project (any size app)

·         In a separate project(s) as a service layer, for large applications that generate view/content specific data. (enterprise apps)

Since a ViewModel is just a class, the easiest way to get started using one is to create a new folder named ViewModels and add a new code file to it.

To create the CustomerViewModel ViewModel, add the Customer and StatesDictionary types as properties to form one CustomerViewModel class. In the example below, the CustomerViewModel class contains the newly defined properties.

public class CustomerViewModel
    public Customer Customer { get; set; }
    public StatesDictionary States { get; set; }
    public CustomerViewModel(Customer customer)
        Customer = customer;
        States = new StatesDictionary();

Generally, ViewModels contain the word "ViewModel" as part of its name; however, the conventions at work here are for consistency in code readability, since other classes in MVC state their intents in their names as well (e.g., names of controllers, action methods, etc...use conventions in their names).

The StatesDictionary class is a simple Dictionary object containing two type parameters of type string. The class also contains the definitions for all the members in the Dictionary (i.e., the state data). The only property in the StatesDictionary class is the StateSelectList, which is an object that Html Helpers use with to render an HTML <select> element that displays a listing of states. The type Dictionary<string, string> in the StateSelectList property maps to the state abbreviation then state name, respectively.

public class StatesDictionary
    public static SelectList StateSelectList
        get { return new SelectList(StateDictionary, "Value", "Key"); }
    public static readonly IDictionary<string, string>
        StateDictionary = new Dictionary<string, string> {
    , { "Alabama", "AL" }
    , { "Alaska", "AK" }
    , { "Arizona", "AZ" }
    , { "Arkansas", "AR" }
    , { "California", "CA" }
    // code continues to add states...

Data that lives in small lists and infrequently changes, like the StatesDictionary class, exists in all types of applications. In real world applications, you'll find a variety of methods for dealing with lookup data such as a list of states - often XML files and SQL tables. You can replace the code in the StateDictionary method to use entities from Entity Framework, read data from files, or any data access code that you require.

After creating the ViewModel, the next steps are to instantiate it in a controller and return it to the view.

Getting the ViewModel to the view

Starts with the controller...

Sending a ViewModel to the view for rendering will work the same as when dealing with a model. Since it's just a class, the view doesn't know, and doesn't care, where the model or ViewModel came from. You can create the instance of the ViewModel class in the controller, or resolve it if using an IoC container. Remember that just as you would do with views, you should keep controllers clean of unnecessary code, meaning that only code that fetches the model or ViewModel belongs here, and little more.

public ActionResult Edit(int id)
    Customer customer = context.Customers.Single(x => x.Id == id);
    var customerViewModel = new CustomerViewModel(customer);
    return View(customerViewModel);

Then the view renders the ViewModel...

In order for the view to know what object to use, set the @model keyword to point to the ViewModel, just like you already would with a regular model.

@model FourthCoffee.Web.ViewModels.CustomerViewModel

Because the Customer object is a property of the ViewModel, you'll see the model.Class.Property syntax to access the ViewModel data, similar to the following line of code.

<div class="editor-label">

    @Html.LabelFor(model => model.Customer.FirstName)
<div class="editor-field">
    @Html.EditorFor(model => model.Customer.FirstName)
    @Html.ValidationMessageFor(model => model.Customer.FirstName)
@* ...View code continues rendering properties... *@

Additionally, you can edit the Edit/Create views so that the DropDownList containing a list of the states will display, and display the correct state matching that of the customer.

<div class="editor-field">   
    @Html.DropDownList("state", new SelectList(StatesDictionary.StateSelectList,

                       "Value", "Text", Model.Customer == null ? "" : Model.Customer.State))
    @Html.ValidationMessageFor(model => model.Customer.State)

As you might have noticed, using a ViewModel is just as easy as using the ViewBag or ViewData objects. ViewModels, however, provide those extra benefits like being easier to test and optimize.

Checking the results

After a user navigates to the /Customers/Edit/1 URL in the browser, the Razor view engine renders the CustomerViewModel similarly to the following screen shot.

The State DropDownList displays the states and the current state for that customer, as expected.

Digging Further into ViewModels

Because ViewModels render pre-manipulated data that no longer have those 1:1 mappings between model classes and database tables, you'll need to do create mappings yourself. You can manually map small ViewModels, but this will quickly become burdensome when mapping larger classes, especially when working with parent-child-grandchild, multi-level, or complex data. This is where a tool such as
AutoMapper comes into play. AutoMapper will let you fluently setup mappings between ViewModels and models more easily than doing so manually, or writing your own mapper.

Here are some tips for using ViewModels:

·         Put only data that you'll render in the ViewModel.

·         The view should direct the properties of the ViewModel, this way it fits better for rendering and maintenance.

·         Use a mapper when ViewModels become complex.

Some tools that can help assist you in generating POCOs (Plain Old CLR Objects) for models and ViewModels are:

POCO Generator

EF POCO Templates

You should always prefer using a ViewModel rather than instantiating multiple models and putting that manipulation code in the controller.


ViewModels help you organize and manage data in MVC applications when you need to work with more complex data than the other objects allow. Using ViewModels gives you the flexibility to use data as you see fit. ViewModels area generally a more flexible way to access multiple data sources than models + ViewBag/ViewData objects.

Reasons why you must trust

Every provider will tell you how they treat their support, uptime, expertise, guarantees, etc., are. Take a close look. What they’re really offering you is nothing close to what ASPHostPortal does. You will be treated with respect and provided the courtesy and service you would expect from a world-class web hosting business.

You’ll have highly trained, skilled professional technical support people ready, willing, and wanting to help you 24 hours a day. Your web hosting account servers are monitored from three monitoring points, with two alert points, every minute, 24 hours a day, 7 days a week, 365 days a year. The followings are the list of other added- benefits you can find when hosting with us:

DELL Hardware
Dell hardware is engineered to keep critical enterprise applications running around the clock with clustered solutions fully tested and certified by Dell and other leading operating system and application providers.
- Recovery Systems
Recovery becomes easy and seamless with our fully managed backup services. We monitor your server to ensure your data is properly backed up and recoverable so when the time comes, you can easily repair or recover your data.
- Control Panel
We provide one of the most comprehensive customer control panels available. Providing maximum control and ease of use, our Control Panel serves as the central management point for your ASPHostPortal account. You’ll use a flexible, powerful hosting control panel that will give you direct control over your web hosting account. Our control panel and systems configuration is fully automated and this means your settings are configured automatically and instantly.
- Excellent Expertise in Technology
The reason we can provide you with a great amount of power, flexibility, and simplicity at such a discounted price is due to incredible efficiencies within our business. We have not just been providing hosting for many clients for years, we have also been researching, developing, and innovating every aspect of our operations, systems, procedures, strategy, management, and teams. Our operations are based on a continual improvement program where we review thousands of systems, operational and management metrics in real-time, to fine-tune every aspect of our operation and activities. We continually train and retrain all people in our teams. We provide all people in our teams with the time, space, and inspiration to research, understand, and explore the Internet in search of greater knowledge. We do this while providing you with the best hosting services for the lowest possible price.
- Data Center
ASPHostPortal modular Tier-3 data center was specifically designed to be a world-class web hosting facility totally dedicated to uncompromised performance and security
- Monitoring Services
From the moment your server is connected to our network it is monitored for connectivity, disk, memory and CPU utilization – as well as hardware failures. Our engineers are alerted to potential issues before they become critical.
- Network
ASPHostPortal has architected its network like no other hosting company. Every facet of our network infrastructure scales to gigabit speeds with no single point of failure.
- Security
Network security and the security of your server are ASPHostPortal’s top priorities. Our security team is constantly monitoring the entire network for unusual or suspicious behavior so that when it is detected we can address the issue before our network or your server is affected.
- Support Services
Engineers staff our data center 24 hours a day, 7 days a week, 365 days a year to manage the network infrastructure and oversee top-of-the-line servers that host our clients’ critical sites and services.