Link to home
Start Free TrialLog in
Avatar of tech1guy
tech1guyFlag 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!
Avatar of jamesbaile
jamesbaile
Flag of United Kingdom of Great Britain and Northern Ireland image

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
Avatar of jamesbaile
jamesbaile
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tech1guy

ASKER

Thanks a lot!!