Reputation: 2245
the database table has fields like this:
fld_column1
fld_column1_item_1
fld_column1_item_2
fld_column1_item_3
fld_column2
fld_column2_item_1
fld_column2_item_2
fld_column2_item_3
fld_column3
fld_column3_item_1
fld_column3_item_2
fld_column3_item_3
and i did this in the controller:
ViewBag.Columns = from col in _db.tbl_columns
select col;
return View();
In the view i did this:
<% foreach (tbl_columns col in (IEnumerable)ViewBag.Columns)
{ %>
<%= col.fld_column1_item1 %>
<%= col.fld_column2_item1 %>
<%= col.fld_column3_item1 %>
<% } %>
Now my qyestion is very simple: is it possible to add a variable that automates this "column1", "column2" etc? And how could I use it?
Upvotes: 1
Views: 1925
Reputation: 4156
I agree with others, you should be using a view model. However, with the current table structure, you will still need to iterate through your model and display each property. If you have the ability to change the db schema I would flatten it out as suggested by George Stocker.
Upvotes: 0
Reputation: 57907
It seems like you could change your table schema and this would be very easy to do at that point.
New Table Schema:
Id Column Item ParentId
1 1 null null
2 1 1 1
3 1 2 1
3 1 3 1
4 2 null null
5 2 1 4
6 2 2 4
6 2 3 4
7 3 null null
8 3 1 7
9 3 2 7
9 3 3 7
Now, you can just iterate through each of them by the following (psuedo-ish code):
foreach (var rows in columns)
{
foreach (var row in rows)
{
<%= row.Item %>
}
}
Upvotes: 1