Difference between Domain Model,ViewModel and EditModel in ASP.NET MVC

We often hear terms like model,view model etc in context of MVC applications. Although these are kind of basic concepts for people who are into ASP.NET MVC for some time (or MVC pattern in general) but can be really confusing for new comers.

I was conducting one interview the other day where I asked the candidate few basic questions on ASP.NET MVC (like how do  you strongly type the views,what is model ,controllers etc) and realized that although he has implemented concepts correctly but is unaware  / confused about terminology.That’s what triggered me to write this post.

So in this post I will try to differentiate between concept of Model,ViewModel and EditModel .
Let’s consider a very simple requirement for an HR application :

Application shall allow user to View, Edit and Save the details of any employee.
Employee name should be highlighted in Green color if his experience lies between 5 to 10 years and Golden color if it is more than 10 years

Now to implement this requirement in any application or technology first thing we will do is to model the entity Employee .Let say we come up with below employee class:

public class Employee
    {
        public int EmployeeId { get; set; }
        public string FirstName { get; set; }
        public string MiddleName { get; set; }
        public string LastName{ get; set; }
        public string Address { get; set; }
        public int Age { get; set; }
        public int YearsOfService { get; set; }
        public Employee Manager { get; set; }
        public Department EmployeeDepartment { get; set; }
    }

Coming to MVC terminology this would be our  “Model” or “Domain Model”. Basically Domain Model consist of those attributes for an Entity which qualifies it in the real world in the context of a particular domain (in this case Human Resource).

From here onwards we would be talking more specific to ASP.NET MVC.

One rule in ASP.NET MVC  has stood the test of time and that is :

All Views Must be Strongly Typed.

What that means is that all your view must have a corresponding model (or simply put a class) associated with it based on which it is rendered and that is also the primary mechanism through which data is exchanged between Views and Controllers.

Coming back to our one line requirement, we need one view to show the details of the employee and another to edit the employee.This essentially means we will need two models, one for viewing employee details and another one for editing the employee details. So the questions comes

Why can’t we use domain model to bind the Views?

Because most of the times our UI requirements are different from domain requirements and if we add attributes to domain model based on UI requirements it will violate OOPS principles viz. SRP or Single responsibility principle.Also it will generate messed up code which have dependencies in all the layers of the code violating separation of concerns.

So based on above requirement our model for viewing employee would look something like:

public class EmployeeViewModel
    {
        [Display(Name = "Name")]
        public string EmployeeName { get; set; }
        [Display(Name = "Address")]
        public string EmployeeAddress { get; set; }

        [Display(Name = "Manager")]
        public string ManagerName { get; set; }

        [Display(Name = "Department")]
        public string DepartmentName { get; set; }

        [Display(Name = "Age")]
        public int Age { get; set; }

        [Display(Name = "Years in Service")]
        public int YearsOfService { get; set; }

        
        public Color YearsOfServiceColor {
            get
            {
                if (YearsOfService < 5)
                    return Color.White;
                else if (YearsOfService < 10)
                    return Color.Green;
                else
                    return Color.Gold;

            }
        }

    }

image

Here we have annotations for display names,Display name is combination of first,middle and last name and properties like YearsOfServiceColor which are all specific to our viewing requirements. This would be our ViewModel.

Next our model for Editing would look something like code shown below:

 public class EmployeeEditModel
    {
        [Required(ErrorMessage = "First Name is Required")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Display(Name = "Middle Name")]
        public string MiddleName { get; set; }

        [Required(ErrorMessage = "Last Name is Required")]
        [Display(Name = "Last Name")]
       public string LastName { get; set; }

        [Display(Name = "Address")]
        public string EmployeeAddress { get; set; }

        [Display(Name = "Age")]
        public SelectList AgeList { get; set; }

        [Display(Name = "Years")]
        public SelectList YearsOfServiceList { get; set; }

        [Display(Name = "Manager")]
        public SelectList Manager { get; set; }

        [Display(Name = "Department")]
        public SelectList Department { get; set; }

        public int ManagerId { get; set; }
        public int DepartmentId { get; set; }
        public int Age { get; set; }
        public int YearsOfService { get; set; }
    }

image

For edit model we see we have different requirement from Domain and View Model.We have required field validations,”SelectList” based properties which will directly bind the dropdownlist on user interface.Also we have a set of id fields which will be used to set the selectedvalues in the dropdownlists(like ManagerId,DepartmentId etc).

Conclusion

So to conclude unlike domain model ,View and Edit models are entities specifically  used in the context of user interface.Also these are not some fixed technical terms which are set in stone.Some people call Edit models as Post Model.Consider you have some kind of reports where you want to have employee details shown.You may want to call it Report Model.Lastly there will be cases where you may want to use your domain model it self for viewing or editing.Its possible ,especially in small applications , but has its own pros and cons.As far as my experience goes keeping all these models separated goes long way in keeping code maintainable and clean.

For further learning, into asp.net MVC you can follow courses in this asp.net MVC 5 learning path.

 

Tagged on: ,

7 thoughts on “Difference between Domain Model,ViewModel and EditModel in ASP.NET MVC

  1. bharat

    Thank You very much for very good article about domain model and view model. I was realy confused with these concept but you saved m1…☺

  2. John

    Thanks.Very nice article.I also was a bit confused about this notions in the sense that they seem very similar in most of the cases (domain model, view model etc.) it can make you think like it’s an unnecesary code duplication.However i’m trying to implement an MVC app and i’m doing researches about the best practices on design it.Shortly i have my data access layer with EF POCO objects,it’s clear for me that the viewmodel it’s totaly different thing.But from what i’ve seen in some posts i don’t get the ideea about Entity Models vs Domain Models, i tend to think that i need my EF Model ,Domain Model and ViewModel.
    But i don’t know i have doubts it seems to mutch to have 2 objects conversions when getting from the ViewModel to the Database.What do you think about this?Should i use my EF POCOs as Domain Models?

    1. Jagmeet Post author

      That is a dilemma lot of people face and there is no right answer. Going by very strict rules of separation of concern you might want to separate your entity and domain model. But you need to visualize this first and see if most of your entity model is same as domain model then it would be an unnecessary exercise. Basic principle which I follow is to keep it simple and if keeping your entity and domain model same keeps it simple, understandable and maintainable then that is the way to go. Also this will be the case for most the applications with less complex domain. But in case your application domain is complex and the size of application is huge e.g. e-commerce applications comprising of multiple modules implemented using different technologies then you would be better off separating these .In such cases you can follow something like a hexagonal architecture or domain driven design.

  3. jinguo

    I am chinese and I am new comers for ASP.NET MVC.I asked some programmer the relationship about domain model and view model,no one Understanding totally . you answer ,i Understanding ,thank you!

    In addition, my English is not good, there are bug forgive me!

  4. Peter Albanese

    Best article yet to explain the difference. For those of us coming from a WebForms or WinForms experiences, this is similar to the properties you had in a Code Behind file. The other importance to a ViewModel is because of automatic property binding, so its important that your ViewModel match your screen controls, regardless of what the fields you are chucking into the database. For example, a ViewModel when you need to do a “Quick Add” for a Person record vs “Advanced Add” for a Person record. Your PersonQuickCreateViewModel may only have Name and Phone properties, while the PersonCreateViewModel will have select lists and a lot of additional properties. This is my two cents.

  5. LEONARDO GOENS

    After a long time, this information is useful.

    Thank you so much.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.