Click below for Step by Step and Interview Q & A (dotnetinter) wrote,
Click below for Step by Step and Interview Q & A

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 customer model 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 indication 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.


What kind of logic view model class will have ?

As the name says view model this class has the gel code or connection code which connects the view and the model.

So the view model class can have following kind of logics:-

  • Color transformation logic: - For example you have a “Grade” property in model and you would like your UI to display “red” color for high level grade, “yellow” color  for low level grade and “green” color of ok grade.

  • Data format transformation logic :- Your model has a property “Status” with “Married” and “Unmarried” value. In the UI you would like to display it as a checkbox which is checked if “married” and unchecked if “unmarried”.

  • Aggregation logic: - You have two different Customer and Address model classes and you have view which displays both “Customer” and “Address” data on one go.

  • Structure downsizing: - You have “Customer” model with “customerCode” and “CustomerName” and you want to display just “CustomerName”. So you can create a wrapper around model and expose the necessary properties.

Tags: mvc interview questions, csharp interview questions, it interview questions with answers, mvc view model interview questions, programming interview questions

  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded