I just get MVC freezing, but yesterday I explored this topic and came to the conclusion that the ViewModel should not directly include the model object. Therefore, I understand that it would be bad practice to include your CustomerModel directly in the CustomerViewModel.
Instead, you want to list all the properties from the CustomerModel that you want to include in your ViewModel. Then you either want to manually map the data from CustomerModel to CustomerViewModel or use a tool like AutoMapper that does this automatically with the same line of code inside your action:
public ViewResult Example() {
In this case, Mapper.Map will return a CustomerViewModel, which you can pass into your view.
You also need to include the following in your Application_Start method:
Mapper.CreateMap<CustomerModel, CustomerViewModel>();
In general, I found that AutoMapper is pretty easy to work with. It automatically if the field names match, if they do not exist or you have a nested object, you can specify these mappings in the CreateMap line. Therefore, if your CustomerModel uses the Address object instead of the individual properties, you should do this:
Mapper.CreateMap<CustomerModel, CustomerViewModel>() .ForMember(dest => dest.StreetAddress, opt => opt.MapFrom(src => src.Address.Street));
Please someone correct me if I am wrong as I just get the head from MVC.
Trent baur
source share