1

If I assign something, anything, could be a string or an int, to ViewData, and I use that in the View. Is that ViewData and ViewBag considered a DTO?

You could assign an object to them, but you don't have to.

Are there times these are and are not considered a Data Transfer Object?

Gilles
  • 5,269
  • 4
  • 34
  • 66
johnny
  • 19,272
  • 52
  • 157
  • 259
  • 1
    This is really just an opinionated question with no real value. Giving a name to a C# object placed in ViewData/ViewBag has no real programming value. IMHO any object placed in VD/VB is not a DTO as it does not transverse any real border. – Erik Philips Jan 04 '18 at 20:35
  • @ErikPhilips I agree that such objects aren't DTOs, I had written an answer but found it could be debated what is an actual DTO. Some people may find it to mean any data structure passed around any classes in the system. – Gilles Jan 04 '18 at 20:36
  • @Gilles You should put that as an answer. The question has programming value because not everyone knows what a DTO is or how to recognize it and if it is an anti-pattern or something else. It may have been better asked on SoftwareEngineering. – johnny Jan 05 '18 at 14:16
  • 1
    @johnny I undeleted my previous answer and modified it a bit. – Gilles Jan 05 '18 at 14:23

2 Answers2

1

Yes, values in Data Transfer Object assigned to ViewData or ViewBag are treated as in same way in view as they are. Like if there is an int type variable in your DTO, in your view you can access it as int through ViewBag. Same case for string and other type variables

Aamir Ali
  • 171
  • 3
  • 11
1

I would personally use the term DTO only when the Data is being transferred across layers, services or applications.

Wikipedia defines it as:

is an object that carries data between processes

Also this highly upvoted answer on StackOverflow says:

A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another.

And:

DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer.

Here we are talking about sending data from the Service Layer to the Web Application which are separate IIS applications not necessarily located on the same machine.

In the case of the ViewBag, you are still on the same layer/subsystem, the Web Application and not crossing any application boundaries.

You could argue that the View and the Controller are different subsystem, but that would be stretching it, as both are in the same compilation unit (the same dll). You could also argue that any class used as a data structure used between two other classes is a DTO but that is not consistent with the commonly held definition of a DTO as all business objects would then qualify as a DTO.

Gilles
  • 5,269
  • 4
  • 34
  • 66