Avatar of tech1guy
tech1guy
Flag for United States of America asked on

ViewModel should contain flat/primitive types OR complex Dto objects

Hello there,

I am using ASP.NET MVC 1.
I have DataTransferObjects like (CustomerDto, OrderDetailDto etc). Each of my View has its own ViewModel class. My question is "What is the BEST practice to create ViewModel".

e.g
Should I only include primtive/flat types in ViewModel as follows:

In this case, I almost need all the elements defined in CustomerDto and OrderDetailsDto.

public class ViewDataForDetailsView
{
    public string customerName;
    public string customerAddress;
    public string orderNumber;
    public string orderDate;
.......
.......
}

OR
can I use existing Dtos as follows:
public class ViewDataForDetailsView
{
    public CustomerDto customerDetails;
    public OrderDetailsDto orderDetails;
}

What are the pros and cons of each of the above metioned methods?

Thanks in advance!
Web Frameworks.NET Programming

Avatar of undefined
Last Comment
tech1guy

8/22/2022 - Mon
jamesbaile

Generally it's considerred good practice to flatten your view model and not present business objects directly in the view. Therefore the first approach is generally considered better than the second.

The reasons for doing this are multiple but in my view the main one is that you don't start building dependancies on the different layers of you application. What happens if your view needs a date formatted in a specific way dependant on the logged in users? This is probably not a business object concern, but specific to the view/presentation layer. If you take the second approach then you will have to start to build into your business layer code to handle view concerns.

How I approach things is to use NHibernate to handle persistence and AutoMapper to convert from business objects to viewmodel objects and only present to the view the information that the view needs. i.e. I wouldn't send a customer business object to the view just so it can display the customer name. I'd specifically code a CustomerName property into my flattened view model.

James

ASKER CERTIFIED SOLUTION
jamesbaile

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
tech1guy

ASKER
Thanks a lot!!
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy