Click here to Skip to main content
15,883,705 members
Articles / All Topics

What is ViewModel in MVC?

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
22 Nov 2015CPOL3 min read 7.7K   3  
People usually get scared and confused when they hear the word View Model in MVC. View Model is a hidden layer in ASP.NET MVC applications. View Model is not a part of MVC. It’s something brought up by community for maintaining SOC.

People usually get scared and confused when they hear the word
View Model in MVC. View Model is a hidden layer in ASP.NET MVC applications.

View Model is not a part of MVC. It’s something brought up by community for maintaining SOC.

SOC –Separation of concerns – It means everyone will do only that which is meant for them. In case of MVC

  • Model will handle Business logic and Business data, it won’t do anything else.
  • Controller will handle only user interaction logic. User interaction logic means logic which will handle the user’s requests.
  • View will contain User interface – Design with user will interact.

Let’s understand Why ViewModel is required when SOC is already implemented in MVC and How ViewModel does that?

Did you even tried to ask yourself this question?

“What all logics do I write?”

If yes this must have been your answer

Let’s talk about each of the above login in conjunction with
ASP.NET MVC(Model View Controller).

Business Logic – Is a part of Model

Database Logic – This is the one of the non-spoken layer in MVC. Many people create a separate layer for this and invoke them from Business layer (model) or some keep them inside Model.

User Interaction logic – written inside controller

Presentation Logic – Presentation logic is the logic which will handle the presentation of a UI. Example – If some value is greater than 100 it should be displayed in green color. Basically it is a part of View.

Data transformation logic – In some situations we have some data with us and we want to display it in a different format. Example we have Date-of-birth and we want to display Age. Again this transformation becomes the part of View.

SOC is violated here because Presentation logic and Data transformation logic is part of view now. View is meant for design so it should not contain any logic and that’s where ViewModel comes to picture. It take out those logic out of view.

Let’s see the demo.

Demo without View Model

Let ‘s say we have model like below.

public class Customer
{
   public string Name { get; set; }
   publicDateTimeDateOfBirth { get; set; }
   publicintSales { get; set; }
}

Our controller code looks like below

public class CustomerController : Controller
{
    publicActionResult Show()
    {
        Customere = GetCustomer();
        return View(e);
    }
    …
}

And Finally View

Customer Detail
Customer Name : @Model. Name
@* Data Transformation logic starts here *@
@{ int age = DateTime.Now.Year – Model.DateOfBirth.Year; if (Model.DateOfBirth > DateTime.Now.AddYears(-age)) { age–; } } Age : @age @* Data Transformation logic ends here *@ @* Presentation logic starts here *@
@if (Model.Sales > 20000) { Sales: @Model.Sales } else { Sales: @Model.Sales } @* Presentation logic ends here *@

Demo with View Model

In this case our model remains same.

Our ViewModel looks like this.

public class CustomerVM
{
   private Customercust { get; set; }

    publicCustomerVM(Customer c1)
    {
         cust= e1;
    }
    public string Name
    {
         get
         {
             return cust.Name;
         }
    }
    public int Age
    {
        get
        {
            int age = DateTime.Now.Year - cust.DateOfBirth.Year;
            if (cust.DateOfBirth>DateTime.Now.AddYears(-age))
            {
                age--;
            }
            return age;
        }
    }
    public string SalesColor
    {
        get
        {
            if(cust.Sales>20000)
            {
                return "red";
            }
            else
            {
                return "green";
            }
        }
    }
}

Controller code will get changed a little bit

public class CustomerController : Controller
{
    public ActionResult Show()
    {
        Customer e = GetCustomer();
        CustomerVM v=new CustomerVM(e);
        return View(v);
    }
    …
}

And finally our simple View

Customer Detail
Name : @Model.Name
Age : @Model.Age
Salary : @Model. Sales

SOC is achieved View is simple design, and presentation logic and data transformation logic is placed in ViewModel.

Is it end?

No, there is one more advantage of View model. In some cases we came up with a requirement where we want to display multiple details in the same view.

Example – Display both Customer and Supplier in the same screen.

In this case we will create a simple class called CustomerSupplierVM as below.

public class CustomerSupplierVM
{
	public Customer customer{get;set;}
	public Supplier supplier{get;set;}
}

This class (view model) will be used for making the view strongly typed view.

See following video on creating simple model using MVC (Model view controller) template: –

<iframe src="//www.youtube.com/embed/0-UdqWy9lVc" width="580" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe>

Hope you enjoyed reading this article. If you are interested in any kind of offline or online corporate or personal trainings on any Microsoft technologies like ASP.NET MVC, WCF, MSBI, WPF, VSTS or non-Microsoft technologies like Design Patterns, jQuery, JSON, Angular.js, Knockout.js etc. visit www.JustCompile.com

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Just Compile
India India
Learning is fun but teaching is awesome.

Who I am? Trainer + consultant + Developer/Architect + Director of Just Compile

My Company - Just Compile

I can be seen in, @sukeshmarla or Facebook

Comments and Discussions

 
-- There are no messages in this forum --