Both Brenden and Liam make great points.
There is nothing that prevents you from writing database queries in your .cshtml
files! If you take this route, assuming your code is correct, your application will run and display content for visitors.
What you will lose is flexibility. How can you apply cross-cutting concerns like authentication, logging, or caching, consistently across a code base? If you don't define "seams" in your application (usually through interfaces/base types), it can be difficult (if not impossible) to apply cross-cutting concerns across a layer.
The difference between creating a custom type that you pass to your View and using a TreeNode
(or some derivation of it) in your View is analogous to this question of defining clear layers.
Did you know that the simple act of reading some properties on TreeNode
instances can execute database queries 🤔? If you pass a TreeNode
to your View and then access those properties you are back to performing database access in the View 😱.
By exposing the most limited set of fields needed for the View to render the Page correctly, you are ensuring that the View is only responsible for presentation and not logic or data access. This forces you to prepare your View Model data, in the layer above, since you don't have access to everything in the View.
This recommendation, to limit what is exposed to your View, is applicable to the rest of the application. Creating classes that represent exactly what is needed at a specific point in time might feel like you are creating too many classes and it's easier to pass TreeNode
instances around...
It's true, it would be easier to pass around TreeNode
instances. Global variables are even easier! But, we all know the eventual costs of these things.
You have the make the decisions for your app that make the most sense - there are different amounts of architecture you can build into your code base. However, View Models that minimize API surface area for Views is a well established pattern and I recommend you take that approach 👍.