Explain the concept of View Model in MVC:-
A view model is a simple class which represents data to be displayed on the view.
For example below is a simple customermodel object with “CustomerName” and “Amount” property.
CustomerViewModel obj = new CustomerViewModel();
obj.Customer.CustomerName = "Shiv";
obj.Customer.Amount = 1000;
But when this “Customer” model object is displayed on the MVC view it looks something as shown in the below figure. It has “CustomerName” , “Amount” plus “Customer Buying Level” fields on the view / screen. “Customer buying Level” is a color indicati on which indicates how aggressive the customer is buying.
“Customer buying level” color depends on the value of the “Amount property. If the amount is greater than 2000 then color is red , if amount is greater than 1500 then color is orange or else the color is yellow.
In other words “Customer buying level” is an extra property which is calculated on the basis of amount.
So the Customer viewmodel class has three properties
- “TxtCustomerName” textbox takes data from “CustomerName” property as it is.
- “TxtAmount” textbox takes data from “Amount” property of model as it is.
- “CustomerBuyingLevelColor” displays color value depending on the “Amount “ value.
Customer Model | Customer ViewModel |
---|---|
CustomerName | TxtCustomerName |
Amount | TxtAmount |
CustomerBuyingLevelColor |