Do you apply View Models in ASP.NET MVC

Matter to discuss is that if Model passing full information to a View, it's straight to use and simple to code too. Then what's matter with ViewModel? when it need to be used? As per industry experience, we have 2 scenarios where it needs to be implemented.

  1. View need to handle 2 Models and both models to be in side a single container
  2. View to handle indicators like, whether a user logged or not? Whether to render a portion or not which are logic belongs to View and we can't keep these under a Model

So you are very much in a position to explain to your client about why need to implement a View Model. Below I am explaining 2 different types of implementation of View Model. The 2nd one will use one more standard layer as Mapper.

1. ViewModel as a type to keep Entity Information and to pass it to the View -

public class MyController : Controller

{

public ActionResult Index()

{

OrderModel orderModel = <<Call to get Model>>

EnquiryModel enquiryModel = <<Call to get Model>>

DetailOrderViewModel viewModel= new DetailOrderViewModel

{

ShouldRenderLoginSection = !User.Identity.IsAuthenticated,

LoggedInName = User.Identity.Name ?? "",

OrderModel = orderModel,

EnquiryModel= enquiryModel

};

returnView(viewModel);

}

}

public classDetailOrderViewModel

{

public bool ShouldRenderLoginSection { get; set; }

public stringLoggedInName { get; set; }

public OrderModel OrderModel { get; set; }

public EnquiryModel EnquiryModel{ get; set; }

}

?

Above you see a scenario to display Order details. Order details may contain enquiry information like whether this order has been came through an inquiry or it's a direct Order etc.. We kept a ViewModel to keep all information and then passed this ViewModelto the View. Here ViewModel is acting as a simple container for multiple entities

2. ViewModel as a type to keep Entity Information through a Mapper -

public class MyController : Controller

{

public ActionResult Index()

{

OrderModel orderModel = <<Call to get Model>>

EnquiryModel enquiryModel = <<Call to get Model>>

DetailOrderViewModel viewModel= MyEntityViewModelMapper.ConvertFromBusinessEntity(orderModel,enquiryModel );

returnView(viewModel);

}

}

public classDetailOrderViewModel

{

public bool ShouldRenderLoginSection { get; set; }

public stringLoggedInName { get; set; }

public OrderModel OrderModel { get; set; }

public EnquiryModel EnquiryModel{ get; set; }

}

public class MyEntityViewModelMapper

{

//Mapping/Assignments here

}

See above implementation that the manual assignment no where applied and it has been moved to a separate Mapper class. This is the preferred implementation as we got clear separation. Now you guys please come up with feed backs as you may have some better suggestions.v

Ebook Download
View all
Learn
View all