Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if else statement around div tag with variable in a cshtml

I am currently having difficulty successfulling adding the following code to my View, which is a .cshtml file.

I have an if and else statement that render different panels depending on a condition.

My code is as follows:

foreach (var item in groupItem)
{
   @if (item.NextDue < DateTime.Today)
   {
     <div class="panel panel-danger" id="panel_@i">
   }
     else
   {
     <div class="panel panel-info" id="panel_@i">
   }
}

I have tried lots of combinations of @{ around the code, but I think that the issue is the ids also have an @ symbol. If I comment out the code within the foreach loop, the code executes fine. However, adding the code into the foreach loop results in an error of "closing } of the foreach loop is not found"

Any help on being able to execute this code would be greatly appreciated.

like image 944
fuzzi Avatar asked Mar 16 '23 03:03

fuzzi


2 Answers

This is how you do it...

    @{
    int[] x = new int[] { 1, 2, 3, 4 };
    string alertClass = "";
}
@foreach (var y in x)
{
    if (y % 2 != 0)
    {
        alertClass = "panel-info";
    }
    else
    {
        alertClass = "panel-danger";
    }
    <div id="panel_@y" class="panel @alertClass">Some Text_@y</div>
}
like image 63
BillRuhl Avatar answered Mar 17 '23 15:03

BillRuhl


The problem is that you have a starting <div> tag but no ending tag, so razor doesn't expect the ending bracket there. You can use the <text> tag to specify what the content is when razor has trouble parsing it:

@foreach (var item in groupItem)
{
   if (item.NextDue < DateTime.Today)
   {
     <text><div class="panel panel-danger" id="panel_@i"></text>
   }
     else
   {
     <text><div class="panel panel-info" id="panel_@i"></text>
   }
}
like image 45
Guffa Avatar answered Mar 17 '23 15:03

Guffa