Reputation: 96
After trying to fill a html table with data from a MVC model, we ran into a problem. This code below generates a table, which is supposed to represent a schedule. The first row displays the days of the week, and the first column displays the number representation of the school hours.
<table class="table2">
<tr>
<th></th>
@{ string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };}
@for (int i = 0; i < days.Length; i++)
{
<th>@(days[i])</th>
}
</tr>
@{
TimeSpan timeSpan = new TimeSpan(8, 30, 0); //08:30:00
TimeSpan AddTime = new TimeSpan(0, 50, 0); //00:50:00
TimeSpan timeSpan2 = new TimeSpan();
}
@{ for (int i = 1; i < 16; i++)
{
<tr>
<td>
<h3>@(i)</h3>
<a>
@{timeSpan.ToString();}
@(string.Format("{0:00}:{1:00}", timeSpan.Hours, timeSpan.Minutes))
</a>
@{timeSpan2 = timeSpan.Add(AddTime);}
<div>
<a>
@(string.Format("{0:00}:{1:00}", timeSpan2.Hours, timeSpan2.Minutes))
@{timeSpan = timeSpan2;}
</a>
</div>
</td>
@foreach (var item in Model)
{
if (item.Hours.Contains(i))
{
for (int x = 0; x < days.Length; x++)
{
if (item.Day != days[x])
{
<td>
</td>
}
else
{
<td>
@(item.Class)
@(item.Classroom)
</td>
}
}
}
}
</tr>
}
}
</table>
Our model looks like this;
public class ScheduleModel
{
[Display(Name = "Lesson Code")]
public string LessonCode { get; set; }
[Display(Name = "Day")]
public string Day { get; set; }
[Display(Name = "Classroom")]
public string Classroom { get; set; }
[Display(Name = "Hours")]
public int[] Hours { get; set; }
[Display(Name = "Class")]
public string Class { get; set; }
}
Ill try to explain what we're trying to do. Our view gets a list of models, filled with the data specified above. We want to display this data in the html table we tried to create above. The "Day" variable corresponds to the days in the top row of the table, and the Hours int[] corresponds to the hours in the first column of the table. These values should be compared with eachother to find the correct spot in the table. We almost got it to work, with the code displayed above, but we ran into a problem with duplicate hours and empty cells.
Lets say we get 2 instances of the model, one looks like this;
Day : Monday
Hours : [1,2,3]
and the second looks like this :
Day : Tuesday
Hours: [1,2,3]
The problem with this is that the foreach loop goes through the first model completly, and fills all cells in the first row with empty cells, then when the foreach loops through the second model, it cannot fill the already created empty cells, so it just sticks them on at the end; screenshot to visualize the problem ;
So it all boils down to this; how do we generate the rows, but in such a way that we can still add new data into the empty fields.
Upvotes: 0
Views: 1759
Reputation: 96
This works perfectly!
@for (int x = 0; x < 7; x++)
{
<td>
@foreach(var item in Model)
{
if (item.Hours.Contains(i))
{
if(item.Day == days[x]){
@(item.Class)
@(item.Classroom)
}
else
{
@("")
}
}
}
</td>
}
Upvotes: 1