user1157885
user1157885

Reputation: 2069

ASP MVC3 Looping through multiple tables not held within your model

I'm new to ASP MVC and have a quick question about accessing data in other tables that aren't part of your @model.

Example:

Right now I have two tables, I'll call them table1 and table2.

I pass table1 out of the controller to the view and then do a foreach loop through that to output its contents.

Within table1 I have a reference to table2 so I can access the fields in table2. What I want is to loop through table2 as well, but I'm unable to do that because the only data that I've output to my model is the contents of table1 so although I can access the data for T2 I can't access information such as how many rows it has.

Upvotes: 0

Views: 300

Answers (1)

Scott Rippey
Scott Rippey

Reputation: 15810

You can either (1) create a new "view model" that contains both tables (as properties our something), or (2) in your controller you can put the second table into the ViewData dictionary, and retrieve it in your view.

The 2nd option is faster and easier, but since this is a pretty common problem, you would be better off getting used to using view models.

(1) Here's an example view model:

public class MyViewModel {
    public SomeDataTable table1 {get; set;}
    public SomeDataTable table2 {get; set;}
}

(2) Here's how to use the ViewData dictionary:

// Controller code (store the table in ViewData):
SomeDataTable table2 = ...;
ViewData["table2"] = table2;

// View code (retrieve the table from ViewData):
<% var table2 = (SomeDataTable)ViewData["table2"]; %>

Upvotes: 1

Related Questions