Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are you populating/validating your ViewModels?

I'm curious of all of the various ways people are building their ViewModels and why they choose that method.

I can think of several ways here:

-1. Injected repository - the controller loads the model and maps to the ViewModel. Here the ViewModel constructor could take various collections to interally set for ex. in a select list such as:

  public CustomerController(ISomeRepository repository) {    _repository = repository; }  public ActionResult Create() {   CustomerCreateViewModel model = new CustomerCreateViewModel(_repository.GetShipTypes,                                                                  _repository.GetStates); .. .. }  

-2. ViewModelBuilder - Either injected or instantiated in the controller with an instance of the injected repository. Called via something like

>var orderViewModel = orderViewModelBuilder.WithStates().Build(orderId);

or,

var orderViewModel = orderViewModelBuilder.WithStates().Build(orderId);

-3. Directly in controller (no code required - its messy)

-4. Some other service (injected or not) that returns domain model which the controller then maps or a ViewModel (anyone doing this to return a view model that isn't specifically named/noted as a ViewModel builder class?)

 public JobCreateViewModel BuildJobCreateViewModel(int parentId) {    JobCreateViewModel model = new JobCreateViewModel();    model.JobStatus = _unitOfWork.JobRepository.GetJobStatuses();    model.States=_unitOfWork.StateRepository.GetAll();    return model; } 

Now on the return trip - regarding validating your view models - are you inheriting from a base ViewModel class for standard validations, or copying your validations (ex. data annotation attributes) between all of your ViewModels, or simply relying on server side validation so it can all be validated againt your domain object?

Any others? Anything better? Why?

EDIT Based on a link below, I did find a nice article from Jimmy Bogard on the architecture of ViewModels. While it doesn't address the question above directly, it's a great reference for anyone coming here for ViewModel information. http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/

like image 502
Adam Tuliper Avatar asked Oct 30 '11 02:10

Adam Tuliper


People also ask

Can Viewmodels have methods?

You can have methods in your ViewModel .

What are Viewmodels in MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

What is the ViewModel responsible for?

The primary responsibility of the ViewModel is to provide data to the view, so that view can put that data on the screen. It also allows the user to interact with data and change the data.

What is MVC validation?

Validation is an important aspect in ASP.NET MVC applications. It is used to check whether the user input is valid. ASP.NET MVC provides a set of validation that is easy-to-use and at the same time, it is also a powerful way to check for errors and, if necessary, display messages to the user.


1 Answers

I inject a service into the controller, not a repository, and then use AutoMapper to convert it into a view model. The benefit of the service layer in this case is that it could aggregate multiple simple operations from one or more repositories into a single operation exposing a domain model. Example:

private readonly ICustomerService _service; public CustomerController(ICustomerService service) {     _service = service; }  [AutoMap(typeof(Customer), typeof(CustomerViewModel))] public ActionResult Create(int id) {     Customer customer = _service.GetCustomer(id);     return View(customer); } 

in this example AutoMap is a custom action filter that I can write which executes after the controller action, inspects the returned object and uses defined AutoMapper mappings to map it to the specified destination type. So the view gets the corresponding CustomerViewModel as model type. Would have been equivalent to:

public ActionResult Create(int id) {     Customer customer = _service.GetCustomer(id);     CustomerViewModel vm = Mapper.Map<Customer, CustomerViewModel>(customer);     return View(vm); } 

it's just that it is too much plumbing and repetitive code that could be centralized.

I would also recommend you watching the putting your controllers on a diet video from Jimmy Bogard.

like image 168
Darin Dimitrov Avatar answered Sep 24 '22 14:09

Darin Dimitrov