Reputation: 3917
Building a quick view that will display a list of all days but only render a header when the day of week changes. Why am I getting a syntax error by the foreach? Any help would be greatly appreciated!
@{
int lastDay = 0;
}
@foreach (var grouping in Model.EventTemplate.EventTemplateSlots) {
if (grouping.Day != lastDay) {
if (lastDay != 0) {
</div>
}
<div style="margin: 5px;"><div class="ui-widget-header ui-corner-all" style="padding: 5px;">@(((DateTime)Model.StartDate).AddDays(grouping.Day).ToShortDateString())</div>
lastDay = grouping.Day;
}
}
Upvotes: 0
Views: 466
Reputation: 29071
This should work:
@{
int lastDay = 0;
<div style="margin: 5px;">
@foreach (var grouping in Model.EventTemplateSlots)
{
if (grouping.Day != lastDay)
{
<div class="ui-widget-header ui-corner-all" style="padding: 5px;">
@(((DateTime)Model.StartDate).AddDays(grouping.Day).ToShortDateString())
</div>
lastDay = grouping.Day;
}
}
</div>
}
Razor prefers that HTML tags match correctly in order to parse the view.
Also note that in your example you'll never get a closing div tag if you don't get a repeat day in your EventTemplateSlots collection.
Upvotes: 0
Reputation: 77606
Razor does not work this way. HTML elements cannot be disjoined as you have it. You have a naked </div>
:
if (lastDay != 0) {
</div>
}
This is invalid as the HTML tags need to be matched similarly to C# braces (they need to be at the same level of nesting and the end tag cannot appear lexically before the start tag). It's not clear to me why you are using that lastDay
check. Why not write it without it like this instead?
@foreach (var grouping in Model.EventTemplate.EventTemplateSlots) {
if (grouping.Day != lastDay) {
<div style="margin: 5px;">
<div class="ui-widget-header ui-corner-all" style="padding: 5px;">@(((DateTime)Model.StartDate).AddDays(grouping.Day).ToShortDateString())</div>
</div>
}
}
This way the start/end HTML tags match up as they need to.
Upvotes: 2
Reputation:
Does your Model implement IEnumerable
? If not, you won't be able to iterate it in a foreach
loop.
What is the error you are seeing? Please post that in your question.
Upvotes: 0