I have a database which has three tables: A, B, and C.
I want the view to render the data in a particular way. Looping through A, then listing rows of B under A where B.aID = A.ID, listing each row of C under each row of B where C.bId = B.ID.
I’m new to ASP.NET MVC3 and I’m not sure how to accomplish this. All the examples I’ve seen are straight forward.
I would start with adding three models: A, B and C. In these models, A contains a List of B’s and B contains a List of C’s. For testing purposes, I would also add something to uniquely identify them, such as a Name. Example:
In my controller, I would add an action method that fills these models with data. For testing purposes, I’m using dummy data.
And for the final piece, the view to display all of this. Simply using @foreach in a nested manner gives us what we need:
Note that the “HelloMvc” is my namespace. You probably need to change this to your own namespace.
Everything put together, this results in a list of A’s with nested B’s and C’s:
(You’ll have to imagine some styling.) Hope this example helps you.
(sidenote)
Funny how that third foreach doesn’t have a ‘@’ in front of it. It’s not a typo or an error, if I put it there, an exception is raised. Small bug in the Razor view engine, I suspect.