In my Controller I have a ProductInfo
class from my Domain Model and I need some of its information to populate my View Model ProductStatsVM
.
How do you populate the View Model? I heard three possible ways:
I know there are tools like AutoMapper, which I am going to use indeed, but before I want to understand the logic on how to fill a View Model from the Controller without using any additional tool.
Right-click in the Store Index action method and select Add View as before, select Genre as the Model class, and press the Add button. This tells the Razor view engine that it will be working with a model object that can hold several Genre objects.
So first create a folder at the root directory of your application with the name ViewModels and then create a class file with the name StudentDetailsViewModel. cs within the ViewModels folder. Once you create the StudentDetailsViewModel. cs class file, then copy and paste the following code in it.
The idea is that your controller action queries some repository to fetch a domain model. Then it passes this domain model to a mapping layer which is responsible to convert it to a view model and finally it passes the view model to the view:
public ActionResult Index(int id)
{
ProductInfo product = repository.GetProductInfo(id);
ProductViewModel viewModel = Mapper.Map<ProductInfo, ProductViewModel>(product);
return View(viewModel);
}
and you could even make your controller slimmer by introducing a custom action filter that will automatically intercept the Model in the OnActionExecuted
event and call into the mapping layer to substitute it with the corresponding view model so that your controller action now becomes:
[AutoMapTo(typeof(ProductViewModel))]
public ActionResult Index(int id)
{
ProductInfo product = repository.GetProductInfo(id);
return View(product);
}
and of course now the view is strongly typed to ProductViewModel:
@model ProductViewModel
...
Up to you to implement the Mapper.Map<TSource, TDest>
method. And if you don't want to implement it yourself you could download AutoMapper which already has this method for you.
The mapping layer is something that is part of the MVC application. It must be aware of both the domain models coming from your service layer and the view models defined in your MVC application in order to be able to perform the mapping.
Don't use constructors (other than the default parameterless one) in your view models. The default model binder will choke if the view model doesn't have a parameterless constructor in your POST actions and you will have to implement custom model binders.
Since viewmodels are needed to populate UI, it should be good idea to get them populated via controllers. You still may keep them slim by using Automapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With