Jammer
Jammer

Reputation: 2410

MVC View if statment inside foreach

I'm trying to put an if statement inside a foreach loop in a Razor view but I get an error Error } expected and if I remove the if statement there are no errors.

I've tried a few different optioned mentioned in other similar questions like wrapping in <text></text>, using @Html.Rawbut all i'm tring to do is set a value for a string variable.

    @foreach (var item in Model)
        {

            string RowColor = "Standard";
            string RowClassName = "row-" + @item.CaseID;
            int StatusDays = int.Parse(@item.StatusDays);

            if (@item.Viewings == 0 && StatusDays >= 14)
            {
                RowColor = "Red";
            }


        <tr class="row-click @RowClassName @RowColor" data-url="/Case/Details/@item.CaseID/">
            <td>
                @Html.DisplayFor(modelItem => item.CaseID)
            </td>
            <td>
                @item.RegistrationDate.Date.ToString("dd-MMM-yyyy")
            </td>
        </tr>
}

Upvotes: 0

Views: 3653

Answers (3)

Luis Tellez
Luis Tellez

Reputation: 2973

Long time without using razor, but I think the problem is you are using more @ inside your code, for example in

 string RowClassName = "row-" + @item.CaseID;
 int StatusDays = int.Parse(@item.StatusDays);

Should be

 string RowClassName = "row-" + item.CaseID;
 int StatusDays = int.Parse(item.StatusDays);

Upvotes: 0

Glenn Packer
Glenn Packer

Reputation: 221

your problem is here

if (@item.Viewings == 0 && StatusDays >= 14)

remove the @ symbol.

if (item.Viewings == 0 && StatusDays >= 14)

Upvotes: 6

Mihir Kale
Mihir Kale

Reputation: 1118

Try this modified code

@{
   foreach (var item in Model)
        {

            string RowColor = "Standard";
            string RowClassName = "row-" + item.CaseID;
            int StatusDays = int.Parse(item.StatusDays);

            if (item.Viewings == 0 && StatusDays >= 14)
            {
                RowColor = "Red";
            }


        <tr class="row-click @RowClassName @RowColor" data-url="/Case/Details/@item.CaseID/">
            <td>
                Html.DisplayFor(modelItem => item.CaseID)
            </td>
            <td>
                item.RegistrationDate.Date.ToString("dd-MMM-yyyy")
            </td>
        </tr>
       }
}

Upvotes: 1

Related Questions