Search code examples
asp.net-mvcdtoviewbagviewdata

Is the ViewData and ViewBag object in ASP.NET MVC a Data Transfer Object (DTO)?


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?


Solution

  • 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.